-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrioQueue.cpp
More file actions
65 lines (55 loc) · 1.4 KB
/
PrioQueue.cpp
File metadata and controls
65 lines (55 loc) · 1.4 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
#include "PrioQueue.h"
PrioQueue::PrioQueue(int maxCapacity) : size(0), capacity(maxCapacity) {
heap = new Node[maxCapacity];
}
PrioQueue::~PrioQueue() {
delete[] heap;
}
void PrioQueue::swap(Node &a, Node &b) {
Node temp = a;
a = b;
b = temp;
}
void PrioQueue::heapUp(int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (heap[parent].time <= heap[index].time) break;
swap(heap[parent], heap[index]);
index = parent;
}
}
void PrioQueue::heapDown(int index) {
while (true) {
int left = 2 * index + 1;
int right = 2 * index + 2;
int smallest = index;
if (left < size && heap[left].time < heap[smallest].time) smallest = left;
if (right < size && heap[right].time < heap[smallest].time) smallest = right;
if (smallest == index) break;
swap(heap[index], heap[smallest]);
index = smallest;
}
}
void PrioQueue::push(Node node) {
if (size >= capacity) {
capacity *= 2;
Node* newHeap = new Node[capacity];
for (int i = 0; i < size; ++i) {
newHeap[i] = heap[i];
}
delete[] heap;
heap = newHeap;
}
heap[size] = node;
heapUp(size);
size++;
}
Node PrioQueue::pop() {
Node top = heap[0];
heap[0] = heap[--size];
heapDown(0);
return top;
}
bool PrioQueue::isEmpty() const {
return size == 0;
}