-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_heap.cpp
More file actions
72 lines (62 loc) · 1.31 KB
/
Copy pathbinary_heap.cpp
File metadata and controls
72 lines (62 loc) · 1.31 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <queue>
using namespace std;
/**
* Array based implementation of the binary heap
* */
template <class T>
class BinHeap {
vector<T> v;
int heap_size;
public:
BinHeap() { heap_size = 0; }
void add(T value) {
++heap_size;
v.push_back(value);
int i = heap_size - 1;
int parent = (i - 1) / 2;
while (i > 0 && v[parent] < v[i]) {
// swap them
swap(v[parent], v[i]);
i = parent;
parent = (i - 1) / 2;
}
}
void heapify(int i) {
int left_child;
int right_child;
int largest_child;
while (true) {
left_child = 2 * i + 1;
right_child = 2 * i + 2;
largest_child = i;
if (left_child < heap_size && v[left_child] > v[largest_child]) {
largest_child = left_child;
}
if (right_child < heap_size && v[right_child] > v[largest_child]) {
largest_child = right_child;
}
if (largest_child == i) {
break;
}
swap(v[i], v[largest_child]);
i = largest_child;
}
}
void print_heap() {
for (int i = 0; i < heap_size; ++i) {
cout << v[i] << " ";
}
cout << endl;
}
};
int main() {
BinHeap<int> binHeap;
binHeap.add(1);
binHeap.add(2);
binHeap.add(3);
binHeap.add(4);
binHeap.add(5);
binHeap.print_heap();
return 0;
}