Skip to content

Commit 30010a0

Browse files
committed
Added custom Heap Sort algorithm for Hacktoberfest 2025
1 parent b9c118f commit 30010a0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

sorting/heap_sorting.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
void heapify(int arr[], int n, int i) {
5+
int largest = i;
6+
int l = 2*i + 1;
7+
int r = 2*i + 2;
8+
if (l < n && arr[l] > arr[largest]) largest = l;
9+
if (r < n && arr[r] > arr[largest]) largest = r;
10+
if (largest != i) {
11+
swap(arr[i], arr[largest]);
12+
heapify(arr, n, largest);
13+
}
14+
}
15+
16+
void heapSort(int arr[], int n) {
17+
for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i);
18+
for (int i = n - 1; i >= 0; i--) {
19+
swap(arr[0], arr[i]);
20+
heapify(arr, i, 0);
21+
}
22+
}
23+
24+
int main() {
25+
int arr[] = {12, 11, 13, 5, 6, 7};
26+
int n = sizeof(arr) / sizeof(arr[0]);
27+
heapSort(arr, n);
28+
cout << "Sorted array: ";
29+
for (int i = 0; i < n; i++) cout << arr[i] << " ";
30+
}

0 commit comments

Comments
 (0)