forked from thisisshub/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap_Sort.cpp
48 lines (40 loc) · 1.04 KB
/
Heap_Sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
void heap(int arr[], int n, int i)
{
int large = i; // Initialize large as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child larger than root
if (l < n && arr[l] > arr[large])
large = l;
// If right child larger than large so far
if (r < n && arr[r] > arr[large])
large = r;
// If largest is not root
if (large != i)
{
swap(arr[i], arr[large]);
heap(arr, n, large);
}
}
// to do heap sort
void heapSort(int arr[], int n)
{
// Build heap
for (int i = n / 2 - 1; i >= 0; i--)
heap(arr, n, i);
// One by one extract an element
for (int i=n-1; i>0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heap on the reduced heap
heap(arr, i, 0);
}
}
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << "\n";
}