-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.cc
70 lines (54 loc) · 1.59 KB
/
heap.cc
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
#include <cstdint>
#include "./probius.hh"
auto heap_sort(Probius &probius) -> void;
static auto sift_down(Probius &probius, std::size_t l, std::size_t r) -> void;
static auto heapify(Probius &probius) -> void;
static auto parent_index(std::size_t idx) -> std::size_t;
static auto lchild_index(std::size_t idx) -> std::size_t;
static auto rchild_index(std::size_t idx) -> std::size_t;
auto main(void) -> int {
Probius probius;
heap_sort(probius);
return 0;
}
static auto heapify(Probius &probius) -> void {
std::size_t r = parent_index(probius.size() - 1);
while (r-- > 0) {
sift_down(probius, r, probius.size() - 1);
}
}
static auto sift_down(Probius &probius, std::size_t l, std::size_t r) -> void {
std::size_t root = l;
while (lchild_index(root) <= r) {
std::size_t candi = root;
if (probius.less(candi, lchild_index(root))) {
candi = lchild_index(root);
}
if (rchild_index(root) <= r && probius.less(candi, rchild_index(root))) {
candi = rchild_index(root);
}
if (candi == root) {
return;
} else {
probius.swap(root, candi);
root = candi;
}
}
}
auto heap_sort(Probius &probius) -> void {
if (probius.size() < 2) {
return;
}
heapify(probius);
std::size_t r = probius.size() - 1;
while (r > 0) {
probius.swap(r, 0);
--r;
sift_down(probius, 0, r);
}
}
static auto parent_index(std::size_t idx) -> std::size_t {
return (idx - 1) / 2;
}
static auto lchild_index(std::size_t idx) -> std::size_t { return 2 * idx + 1; }
static auto rchild_index(std::size_t idx) -> std::size_t { return 2 * idx + 2; }