-
Notifications
You must be signed in to change notification settings - Fork 0
/
priority-queue-heap.cpp
94 lines (74 loc) · 1.85 KB
/
priority-queue-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
92
93
94
#include <iostream>
using namespace std;
class Heap {
public:
int elements[20] {};
int size;
Heap() {
this -> size = 0;
}
void add(int value) {
this -> elements[++size] = value;
bubbleUp(size);
}
void remove() {
this -> elements[1] = this -> elements[this -> size--];
bubbleDown(1);
}
void bubbleUp(int index) {
int parent = index / 2;
while(parent >= 1 && this -> elements[parent] > this -> elements[index]) {
swap(this -> elements[parent], this -> elements[index]);
index = parent;
parent = parent / 2;
}
}
void bubbleDown(int index) {
int minChild;
while(index < this -> size) {
minChild = -1;
if(index * 2 <= this -> size)
minChild = index * 2;
if(index * 2 + 1 <= this -> size && this -> elements[index * 2 + 1] < this -> elements[index * 2])
minChild = index * 2 + 1;
if(minChild != -1 && this -> elements[minChild] < this -> elements[index]) {
swap(this -> elements[index], this -> elements[minChild]);
index = minChild;
} else {
index = this -> size + 1;
}
}
}
int getMin() {
return this -> elements[1];
}
};
class PriorityQueue {
public:
Heap heap;
void push(int value) {
this -> heap.add(value);
}
void pop() {
this -> heap.remove();
}
int top() {
return this -> heap.getMin();
}
};
int main() {
PriorityQueue pq;
pq.push(5);
pq.push(2);
pq.push(6);
pq.push(8);
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
return 0;
}