From 577b37d0c03f6fb42c715b20e25d0bc9a8003834 Mon Sep 17 00:00:00 2001 From: Kuljeet-123 Date: Fri, 24 Jul 2020 21:29:51 +0530 Subject: [PATCH] Heap Sort --- .../Heap Sort/SolutionByKuljeet.cpp | 50 +++++++++++++++++++ .../Array Or Vector/Heap Sort/readMe.md | 19 +++++++ 2 files changed, 69 insertions(+) create mode 100644 Data Structure/Array Or Vector/Heap Sort/SolutionByKuljeet.cpp create mode 100644 Data Structure/Array Or Vector/Heap Sort/readMe.md diff --git a/Data Structure/Array Or Vector/Heap Sort/SolutionByKuljeet.cpp b/Data Structure/Array Or Vector/Heap Sort/SolutionByKuljeet.cpp new file mode 100644 index 000000000..ce70ffd48 --- /dev/null +++ b/Data Structure/Array Or Vector/Heap Sort/SolutionByKuljeet.cpp @@ -0,0 +1,50 @@ +#include +#include +using namespace std; + +void maxHeapify(int arr[], int n, int i) +{ + int largest = i, left = 2*i+1, right = 2*i+2; + if(left < n && arr[left] > arr[largest]) + largest = left; + + if(right < n && arr[right] > arr[largest]) + largest = right; + + if(largest != i) + { + swap(arr[largest],arr[i]); + maxHeapify(arr,n,largest); + } +} + +void build(int arr[], int n) +{ + for(int i = (n-2)/2;i >= 0;i--) + maxHeapify(arr,n,i); +} + +void heapSort(int arr[], int n) +{ + build(arr,n); + for(int i = n-1;i >= 1;i--) + { + swap(arr[0],arr[i]); + maxHeapify(arr,i,0); + } + + + for(int i = 0;i < n;i++) + cout << arr[i] << " "; +} + +int main() +{ + int n; + cin >> n; + int arr[n]; + for(int i = 0;i < n;i++) + cin >> arr[i]; + heapSort(arr,n); + return 0; +} \ No newline at end of file diff --git a/Data Structure/Array Or Vector/Heap Sort/readMe.md b/Data Structure/Array Or Vector/Heap Sort/readMe.md new file mode 100644 index 000000000..3b344ae24 --- /dev/null +++ b/Data Structure/Array Or Vector/Heap Sort/readMe.md @@ -0,0 +1,19 @@ +# An unsorted array is given sort the array using heap sort. + +# Constraints +- 1 < size Of Array <= 10^6 +- 0 < Array Elements <= 10^9 + +# Input +- Array +- Its Size + +# Output +- Print the sorted array. + +``` +Input : {12, 11, 13, 5, 6, 7} +Output : { 5, 6, 7, 11, 12, 13, } + +``` +