-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.cpp
More file actions
50 lines (28 loc) · 765 Bytes
/
Copy pathHeapSort.cpp
File metadata and controls
50 lines (28 loc) · 765 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
#include "HeapSort.h"
void HeapSort::Sort() {
const int LEN = nums.size();
for (int i = LEN - 1; i >= 0; --i)
heapify(i, LEN);
for (int i = LEN - 1; i > 0; --i) {
swapVisual(0, i);
heapify(0, i);
}
}
int HeapSort::left(int idx) {
return 2 * idx + 1;
}
int HeapSort::right(int idx) {
return 2 * idx + 2;
}
void HeapSort::heapify(int idx, int n) {
int next_idx = idx;
do {
idx = next_idx;
next_idx = idx;
if (left(idx) < n && *nums[left(idx)] > *nums[next_idx])
next_idx = left(idx);
if (right(idx) < n && *nums[right(idx)] > *nums[next_idx])
next_idx = right(idx);
swapVisual(idx, next_idx);
} while (next_idx != idx);
}