-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortHeap.cc
More file actions
58 lines (50 loc) · 1.15 KB
/
SortHeap.cc
File metadata and controls
58 lines (50 loc) · 1.15 KB
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
#include <format>
#include <iostream>
#include <random>
#include <span>
#include "vector.hh"
/**
* (k-1)/2
* |
* k
* / \
* 2k+1 2k+2
*/
template <typename compar>
struct heap {
static void sort(std::span<compar> pq) {
int n = pq.size() - 1;
// heapify phase
for (int k = (n - 1) / 2; k >= 0; --k) sink(pq, k, n);
// sortdown phase
while (n > 0) {
std::swap(pq[0], pq[n--]);
sink(pq, 0, n);
}
}
static void sink(std::span<compar> pq, int k, int n) {
while (2 * k + 1 <= n) {
int j{2 * k + 1};
if (j < n && pq[j] < pq[j + 1]) ++j;
if (pq[k] >= pq[j]) break;
std::swap(pq[k], pq[j]);
k = j;
}
}
};
int main() {
std::mt19937 mt(std::random_device{}());
std::uniform_int_distribution rand(10, 99);
ns::vector<int> A(16);
for (auto &e : A) {
e = rand(mt);
std::cout << e << '\t';
}
std::cout << "\n\n";
heap<int>::sort(A);
std::ranges::for_each(A, [](auto x) { std::cout << x << '\t'; });
std::cout << "\n\n";
std::cout << std::format("{}",
std::ranges::is_sorted(A) ? "Sorted" : "Unsorted");
std::cout << '\n';
}