From fad458e794af44c4c522637e5dcd55e087be4001 Mon Sep 17 00:00:00 2001 From: Agam118 <87620190+Agam118@users.noreply.github.com> Date: Sat, 15 Oct 2022 20:14:05 +0530 Subject: [PATCH] Heap Sort --- Heap_Sort.cpp | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Heap_Sort.cpp diff --git a/Heap_Sort.cpp b/Heap_Sort.cpp new file mode 100644 index 0000000..a0a4caa --- /dev/null +++ b/Heap_Sort.cpp @@ -0,0 +1,69 @@ +// C++ program for implementation of Heap Sort + +#include +using namespace std; + + +void heapify(int arr[], int N, int i) +{ + + + int large = i; + + + int l = 2 * i + 1; + + int r = 2 * i + 2; + + + if (l < N && arr[l] > arr[large]) + large = l; + + if (r < N && arr[r] > arr[large]) + large = r; + + if (large != i) { + swap(arr[i], arr[large]); + + heapify(arr, N, large); + } +} + + +void heapSort(int arr[], int N) +{ + + for (int i = N / 2 - 1; i >= 0; i--) + heapify(arr, N, i); + + + for (int i = N - 1; i > 0; i--) { + + + swap(arr[0], arr[i]); + + + heapify(arr, i, 0); + } +} + + +void printArray(int arr[], int N) +{ + for (int i = 0; i < N; ++i) + cout << arr[i] << " "; + cout << "\n"; +} + + +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int N = sizeof(arr) / sizeof(arr[0]); + + // Function call + heapSort(arr, N); + + cout << "Sorted array is \n"; + printArray(arr, N); +}