-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.cpp
More file actions
76 lines (68 loc) · 1.69 KB
/
Heap.cpp
File metadata and controls
76 lines (68 loc) · 1.69 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
73
74
75
76
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
template <typename T, typename Compare = less<T>>
class Heap
{
private:
vector<T> data;
Compare comp; // comparator: less = min-heap, greater = max-heap
void heapify_up(int idx)
{
while (idx > 0)
{
int parent = (idx - 1) / 2;
if (comp(data[idx], data[parent]))
{
swap(data[idx], data[parent]);
idx = parent;
}
else
break;
}
}
void heapify_down(int idx)
{
int n = data.size();
while (true)
{
int left = 2 * idx + 1, right = 2 * idx + 2, smallest = idx;
if (left < n && comp(data[left], data[smallest]))
smallest = left;
if (right < n && comp(data[right], data[smallest]))
smallest = right;
if (smallest != idx)
{
swap(data[idx], data[smallest]);
idx = smallest;
}
else
break;
}
}
public:
Heap(Compare c = Compare()) : comp(c) {}
bool empty() const { return data.empty(); }
int size() const { return data.size(); }
const T &top() const
{
if (empty())
throw runtime_error("Heap is empty!");
return data[0];
}
void push(const T &value)
{
data.push_back(value);
heapify_up(data.size() - 1);
}
void pop()
{
if (empty())
throw runtime_error("Heap is empty!");
data[0] = data.back();
data.pop_back();
if (!empty())
heapify_down(0);
}
};