Skip to content

Commit cd3301d

Browse files
authored
Added Heap Sort
1 parent 93b6cd8 commit cd3301d

File tree

1 file changed

+66
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)