-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority_queue.js
More file actions
70 lines (55 loc) · 1.24 KB
/
priority_queue.js
File metadata and controls
70 lines (55 loc) · 1.24 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
class PriorityQueue {
constructor() {
this.heap = [];
}
isEmpty() {
return this.heap.length === 0;
}
swap(idx1, idx2) {
[this.heap[idx1], this.heap[idx2]] = [this.heap[idx2], this.heap[idx1]];
}
insert(node, priority) {
this.heap.push([node, priority]);
this.bubbleUp();
}
bubbleUp() {
let idx = this.heap.length - 1;
let parentIdx = Math.floor((idx - 1) / 2);
while (parentIdx >= 0 && this.heap[idx][1] < this.heap[parentIdx][1]) {
this.swap(idx, parentIdx);
idx = parentIdx;
parentIdx = Math.floor((idx - 1) / 2);
}
}
delete() {
if (this.isEmpty()) return null;
const rootNode = this.heap[0];
const lastNode = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = lastNode;
this.bubbleDown();
}
return rootNode;
}
bubbleDown() {
let idx = 0;
while (true) {
let leftIdx = idx * 2 + 1;
let rightIdx = idx * 2 + 2;
let smallestIdx = idx;
if (
this.heap[leftIdx] &&
this.heap[leftIdx][1] < this.heap[smallestIdx][1]
)
smallestIdx = leftIdx;
if (
this.heap[rightIdx] &&
this.heap[rightIdx][1] < this.heap[smallestIdx][1]
)
smallestIdx = rightIdx;
if (smallestIdx === idx) break;
this.swap(idx, smallestIdx);
idx = smallestIdx;
}
}
}