-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapSort.cpp
More file actions
54 lines (42 loc) · 758 Bytes
/
heapSort.cpp
File metadata and controls
54 lines (42 loc) · 758 Bytes
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
#include <bits/stdc++.h>
using namespace std;
vector<int> ar = {2, 7, 4, 10};
class Solution
{
public:
void Heapify(int s, int i)
{
int root = i;
int leftChi = 2 * i + 1;
int rightChi = 2 * i + 2;
if (leftChi < s && ar[leftChi] > ar[root])
root = leftChi;
if (rightChi < s && ar[rightChi] > ar[root])
root = rightChi;
if (root != i)
{
swap(ar[root], ar[i]);
Heapify(s, root);
}
}
void HeapSort(int s)
{
if (s - 1 == 0)
return;
swap(ar[s - 1], ar[0]);
s--;
Heapify(s, 0);
HeapSort(s);
}
};
int main()
{
Solution solution;
for (int i = ar.size() / 2 - 1; i > -1; i--)
solution.Heapify(ar.size(), i);
solution.HeapSort(ar.size());
for (auto x : ar)
cout << x << " ";
cout << endl;
return 0;
}