Skip to content

Commit cae02bb

Browse files
authored
create heap sort in c++
1 parent 41ab20d commit cae02bb

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

heap sort.cpp

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

0 commit comments

Comments
 (0)