-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cpp
More file actions
87 lines (77 loc) · 1.62 KB
/
heap.cpp
File metadata and controls
87 lines (77 loc) · 1.62 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
77
78
79
80
81
82
83
84
85
86
87
//min heap
template<typename T>
class Heap {
vector<T> heap;
int heap_size;
int parent(int i) const { return (i - 1) / 2; }
int left(int i) const { return 2 * i + 1; }
int right(int i) const { return 2 * i + 2; }
//make subtree rooted at index i a min heap
void min_heapify(int i) {
int L = left(i);
int R = right(i);
int smallest;
if (L < heap_size && heap[L] < heap[i])
smallest = L;
else
smallest = i;
if (R < heap_size && heap[R] < heap[smallest])
smallest = R;
if (smallest != i) {
swap(heap[smallest], heap[i]);
min_heapify(smallest);
}
}
//turn heap into a min heap
void build_heap() {
heap_size = heap.size();
for (int i = heap.size() / 2 - 1; i >= 0; --i)
min_heapify(i);
}
public:
Heap(vector<T>& initial_list)
: heap(initial_list)
{
build_heap();
}
T get_min() const {
return heap[0];
}
T extract_min() {
if (heap_size < 1) {
//raise exception
}
T min = heap[0];
heap[0] = heap[heap_size - 1];
--heap_size;
min_heapify(0);
return min;
}
void decrease_key(T item, T key) {
auto it = find(heap.begin(), heap.end(), item);
int i;
if (it == heap.end()) {
//raise exception
return;
}
else {
i = it - heap.begin();
}
heap[i] = key;
while (i > 0 && heap[parent(i)] > heap[i]) {
swap(heap[i], heap[parent(i)]);
i = parent(i);
}
}
bool contains(T key) {
auto it = find(heap.begin(), heap.end(), key);
if (it - heap.begin() >= heap_size)
return false;
return true;
}
bool empty() {
if (heap_size < 1)
return true;
return false;
}
};