-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm_heap_01.cc
80 lines (65 loc) · 2.01 KB
/
algorithm_heap_01.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
71
72
73
74
75
76
77
78
79
//
// Program
// <algorithm> @ make_heap, sort_heap usage.
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -o algorithm_heap_01 algorithm_heap_01.cc
//
// Execution
// ./algorithm_heap_01
//
#include <iostream>
#include <vector>
#include <algorithm>
static std::ostream& operator<< (std::ostream& out, const std::vector<int>& vec) {
for (const auto& num: vec) {
out << num << " ";
}
return out;
}
//
// Entry function
//
int main() {
std::cout <<"\n--- [make_heap] ---\n";
{
std::vector<int> vec { 2, 5, 3, 6, 1, 9, 0 };
std::cout << "Input: " << vec << '\n';
std::cout << "is_heap: " << std::boolalpha
<< std::is_heap(vec.begin(), vec.end())
<< '\n';
// Arrange our vector into Max Heap arrangement
std::make_heap(vec.begin(), vec.end());
std::cout << "After make_heap: " << vec << '\n';
std::cout << "is_heap: " << std::boolalpha
<< std::is_heap(vec.begin(), vec.end())
<< '\n';
}
std::cout <<"\n--- [sort_heap] ---\n";
{
std::vector<int> vec { 2, 5, 3, 6, 1, 9, 0 };
std::cout << "Input: " << vec << '\n';
std::cout << "is_heap: " << std::boolalpha
<< std::is_heap(vec.begin(), vec.end())
<< '\n';
// Arrange ascending order - heap property is lost
std::sort_heap(vec.begin(), vec.end());
std::cout << "After sort_heap: " << vec << '\n';
std::cout << "is_heap: " << std::boolalpha
<< std::is_heap(vec.begin(), vec.end())
<< '\n';
}
return 0;
}
/*
--- [make_heap] ---
Input: 2 5 3 6 1 9 0
is_heap: false
After make_heap: 9 6 3 5 1 2 0
is_heap: true
--- [sort_heap] ---
Input: 2 5 3 6 1 9 0
is_heap: false
After sort_heap: 0 1 3 6 9 5 2
is_heap: false
*/