From 2a11137efe4b582e4c443d0bb1209968c6c88f9c Mon Sep 17 00:00:00 2001 From: HeYPoonam <115446295+HeYPoonam@users.noreply.github.com> Date: Thu, 13 Oct 2022 19:59:14 +0530 Subject: [PATCH] Create HeapSort.cpp --- HeapSort.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 HeapSort.cpp diff --git a/HeapSort.cpp b/HeapSort.cpp new file mode 100644 index 0000000..2ab9d41 --- /dev/null +++ b/HeapSort.cpp @@ -0,0 +1,61 @@ + +#include +using namespace std; + +void heapify(int arr[], int n, int i) +{ + int largest = i; // Initialize largest as root + int l = 2 * i + 1; // left = 2*i + 1 + int r = 2 * i + 2; // right = 2*i + 2 + + + if (l < n && arr[l] > arr[largest]) + largest = l; + + + if (r < n && arr[r] > arr[largest]) + largest = r; + + + if (largest != i) { + swap(arr[i], arr[largest]); + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + +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--) { + // Move current root to end + 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]); + + heapSort(arr, n); + + cout << "Sorted array is \n"; + printArray(arr, n); +}