-
Notifications
You must be signed in to change notification settings - Fork 5
/
min_heap.cpp
91 lines (68 loc) · 1.54 KB
/
min_heap.cpp
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
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
class MinHeap {
private:
vector <int> heap;
int parent(int n) {
return (n - 1) >> 1;
}
int left(int n) {
return (n << 1) + 1;
}
int right(int n) {
return (n << 1) + 2;
}
public:
void push(int element) {
heap.push_back(element);
int i = heap.size() - 1;
while (i != 0 && heap[i] < heap[parent(i)]) {
swap(heap[i], heap[parent(i)]);
i = parent(i);
}
}
int peek() {
return heap[0];
}
int pop() {
int head = heap[0];
int size = heap.size();
heap[0] = heap[size-1];
heap.pop_back();
min_heapify(0);
return head;
}
void min_heapify(int pos) {
int l = left(pos);
int r = right(pos);
int smallest = pos;
if (l < heap.size() && heap[l] < heap[smallest]) smallest = l;
if (r < heap.size() && heap[r] < heap[smallest]) smallest = r;
if (smallest != pos) {
swap(heap[smallest], heap[pos]);
min_heapify(smallest);
}
}
int size() {
return heap.size();
}
};
int main() {
MinHeap h;
h.push(12);
h.push(1);
h.push(9);
h.push(21);
cout << "size: " << h.size() << endl;
cout << "popped: " << h.pop() << endl;
cout << "popped: " << h.pop() << endl;
cout << "popped: " << h.pop() << endl;
cout << "popped: " << h.pop() << endl;
}
/*
size: 4
popped: 1
popped: 9
popped: 12
popped: 21
*/