From 30010a012ea1cc60c89df5cb674e9c94fc6f0a26 Mon Sep 17 00:00:00 2001 From: chintansood Date: Sat, 18 Oct 2025 18:47:28 +0530 Subject: [PATCH] Added custom Heap Sort algorithm for Hacktoberfest 2025 --- sorting/heap_sorting.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 sorting/heap_sorting.cpp diff --git a/sorting/heap_sorting.cpp b/sorting/heap_sorting.cpp new file mode 100644 index 00000000000..70842ec63f8 --- /dev/null +++ b/sorting/heap_sorting.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +void heapify(int arr[], int n, int i) { + int largest = i; + int l = 2*i + 1; + int r = 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]); + 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--) { + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} + +int main() { + int arr[] = {12, 11, 13, 5, 6, 7}; + int n = sizeof(arr) / sizeof(arr[0]); + heapSort(arr, n); + cout << "Sorted array: "; + for (int i = 0; i < n; i++) cout << arr[i] << " "; +}