forked from iharsh234/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Heap_Sort.cpp
65 lines (53 loc) · 1.18 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
void Heapify(int array[], int root, int size)
{
int left = 2 * root + 1, largest;
int right = left + 1, temp;
if(left < size && array[left] > array[root])
largest = left;
else
largest = root;
if(right < size && array[right] > array[largest])
largest = right;
if(largest != root)
{
temp = array[root];
array[root] = array[largest];
array[largest] = temp;
Heapify(array, largest, size);
}
}
void Build_Heap(int array[], int size)
{
for(int i = (size - 1) / 2; i >= 0; i--)
Heapify(array, i, size);
}
void Heap_Sort(int array[], int size)
{
Build_Heap(array, size);
int temp, i;
for(i = size - 1; i > 0; i--)
{
temp = array[0];
array[0] = array[i];
array[i] = temp;
Heapify(array, 0, i);
}
}
// Function to print elements of array
void Print_Array(int array[], int size)
{
for(int i = 0; i < size; i++)
cout << array[i] << " ";
cout << endl;
}
int main()
{
int array[] = {2, 4, 3, 1, 6, 8, 4};
Heap_Sort(array, 7);
Print_Array(array, 7);
return 0;
}
// Output
// 1 2 3 4 4 6 8