Skip to content

Commit 5bebaf9

Browse files
Merge pull request #422 from aishalg/patch-2
Create Heap Sort in C++
2 parents e9afc9f + 98b0cfc commit 5bebaf9

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

CPP/sorting/Heap Sort in C++

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// C++ program for implementation of Heap Sort
2+
3+
#include <iostream>
4+
using namespace std;
5+
6+
// To heapify a subtree rooted with node i
7+
// which is an index in arr[].
8+
// n is size of heap
9+
void heapify(int arr[], int N, int i)
10+
{
11+
12+
// Initialize largest as root
13+
int largest = i;
14+
15+
// left = 2*i + 1
16+
int l = 2 * i + 1;
17+
18+
// right = 2*i + 2
19+
int r = 2 * i + 2;
20+
21+
// If left child is larger than root
22+
if (l < N && arr[l] > arr[largest])
23+
largest = l;
24+
25+
// If right child is larger than largest
26+
// so far
27+
if (r < N && arr[r] > arr[largest])
28+
largest = r;
29+
30+
// If largest is not root
31+
if (largest != i) {
32+
swap(arr[i], arr[largest]);
33+
34+
// Recursively heapify the affected
35+
// sub-tree
36+
heapify(arr, N, largest);
37+
}
38+
}
39+
40+
// Main function to do heap sort
41+
void heapSort(int arr[], int N)
42+
{
43+
44+
// Build heap (rearrange array)
45+
for (int i = N / 2 - 1; i >= 0; i--)
46+
heapify(arr, N, i);
47+
48+
// One by one extract an element
49+
// from heap
50+
for (int i = N - 1; i > 0; i--) {
51+
52+
// Move current root to end
53+
swap(arr[0], arr[i]);
54+
55+
// call max heapify on the reduced heap
56+
heapify(arr, i, 0);
57+
}
58+
}
59+
60+
// A utility function to print array of size n
61+
void printArray(int arr[], int N)
62+
{
63+
for (int i = 0; i < N; ++i)
64+
cout << arr[i] << " ";
65+
cout << "\n";
66+
}
67+
68+
// Driver's code
69+
int main()
70+
{
71+
int arr[] = { 12, 11, 13, 5, 6, 7 };
72+
int N = sizeof(arr) / sizeof(arr[0]);
73+
74+
// Function call
75+
heapSort(arr, N);
76+
77+
cout << "Sorted array is \n";
78+
printArray(arr, N);
79+
}

0 commit comments

Comments
 (0)