This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap_Sort.cpp
80 lines (68 loc) · 1.39 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#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 n, i;
cout<<"Enter number of elements in your array: ";
cin>>n;
int array[n];
cout<<"Enter your array: ";
for (i = 0; i < n; i++)
{
cin>>array[i];
}
Heap_Sort(array, n);
Print_Array(array, n);
return 0;
}
/*Enter number of elements in your array: 7
Enter your array: 2
4
3
1
6
8
4
1 2 3 4 4 6 8*/