forked from AlexLai1990/LintCode_OJ_-_-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.cpp
51 lines (45 loc) · 1.17 KB
/
HeapSort.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
class Solution {
public:
/**
* @param A: Given an integer array
* @return: void
*/
void heapify(vector<int> &A) {
// write your code here
createMaxHeap(A);
for (int i = A.size() - 1; i > 0; i--) {
swap(A[0], A[i]);
fixDown(A, 0, i);
}
return;
}
void createMaxHeap(vector<int> &A) {
for (int i = A.size() - 1 ; i >= 0; i--) {
fixDown(A, i, A.size());
}
return;
}
void fixDown(vector<int> &A, int curr_index, int size) {
while (left_child(curr_index) < size) {
int max_child_index = left_child(curr_index);
if (right_child(curr_index) < size) {
if (A[max_child_index] < A[right_child(curr_index)])
max_child_index = right_child(curr_index);
}
if (A[curr_index] < A[max_child_index]) {
swap(A[curr_index], A[max_child_index]);
}
curr_index = max_child_index;
}
return;
}
int get_parent(int index) {
return ((index + 1) / 2) - 1;
}
int left_child(int index) {
return index * 2 + 1;
}
int right_child(int index) {
return index * 2 + 2;
}
};