-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPriorityQueue.js
68 lines (60 loc) · 1.81 KB
/
PriorityQueue.js
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
class Node {
constructor(val, priority) {
this.value = val;
this.priority = priority;
this.next = null;
}
}
class PriorityQueue {
constructor() {
this.heap = [ null ]
}
insert(value, priority) {
const newNode = new Node(value, priority);
this.heap.push(newNode);
let currentNodeIdx = this.heap.length - 1;
let currentNodeParentIdx = Math.floor(currentNodeIdx / 2);
while (
this.heap[currentNodeParentIdx] &&
newNode.priority > this.heap[currentNodeParentIdx].priority
) {
const parent = this.heap[currentNodeParentIdx];
this.heap[currentNodeParentIdx] = newNode;
this.heap[currentNodeIdx] = parent;
currentNodeIdx = currentNodeParentIdx;
currentNodeParentIdx = Math.floor(currentNodeIdx / 2);
}
}
remove() {
if (this.heap.length < 3) {
const toReturn = this.heap.pop();
this.heap[0] = null;
return toReturn;
}
const toRemove = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIdx = 1;
let [left, right] = [2*currentIdx, 2*currentIdx + 1];
let currentChildIdx = this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left;
while (this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority) {
let currentNode = this.heap[currentIdx]
let currentChildNode = this.heap[currentChildIdx];
this.heap[currentChildIdx] = currentNode;
this.heap[currentIdx] = currentChildNode;
}
return toRemove;
}
front() {
if (this.heap[0] === null) {
return {
first: 8e-38,
second: 0
};
}
return this.heap[0].value;
}
size() {
return this.heap.length;
}
}
module.exports = PriorityQueue;