From 47abcde08355f9b2059129922dc518c052936939 Mon Sep 17 00:00:00 2001 From: mohibqureshi <45489713+mohibqureshi@users.noreply.github.com> Date: Tue, 8 Oct 2019 19:31:59 +0530 Subject: [PATCH] Create heap_sort.cpp --- Algorithms/sorting/heap_sort.cpp | 68 ++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Algorithms/sorting/heap_sort.cpp diff --git a/Algorithms/sorting/heap_sort.cpp b/Algorithms/sorting/heap_sort.cpp new file mode 100644 index 0000000..d1cd899 --- /dev/null +++ b/Algorithms/sorting/heap_sort.cpp @@ -0,0 +1,68 @@ +#include + +using namespace std; + +void MaxHeapify(int A[], int len, int i) +{ + int left = 2 * i; + int right = (2 * i + 1); + int large = i; + if (left < len && A[left] > A[i]) + { + large = left; + } + else + large = i; + + if (right < len && A[right] > A[large]) + { + large = right; + } + if (large != i) + { + swap(A[i], A[large]); + MaxHeapify(A, len, large); + } +} + +void buildmaxheap(int A[], int n) +{ + int heapsize; + heapsize = n; + for (int i = (n / 2) - 1; i >= 0; i--) + { + MaxHeapify(A, n, i); + } +} + +void HeapSort(int A[], int n) +{ + buildmaxheap(A, n); + for (int i = n - 1; i >= 0; i--) + { + swap(A[0], A[i]); + MaxHeapify(A, i, 0); + } +} + +int main() +{ + int n; + cout << "Enter the length of array" << endl; + cin >> n; + int arr[n]; + cout << "Enter array elements(space separated):" << endl; + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + HeapSort(arr, n); + cout << "The sorted array is:" << endl; + for (int i = 0; i < n; i++) + { + cout << arr[i] << " "; + } + cout << endl; + + return 0; +}