-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriorityQueue.js
89 lines (77 loc) · 2.11 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class Node {
constructor(val, priority) {
this.value = val;
this.priority = priority;
}
}
// Uses a Min Binary Heap
class PriorityQueue {
constructor() {
this.values = [];
}
enqueue(val, priority) {
const newNode = new Node(val, priority);
this.values.push(newNode);
this.bubbleUp();
return this.values;
}
bubbleUp() {
let elementIndex = this.values.length - 1;
const element = this.values[elementIndex];
while (elementIndex > 0) {
let parentIndex = Math.floor((elementIndex - 1) / 2);
let parent = this.values[parentIndex];
if (parent.priority < element.priority) break;
this.values[parentIndex] = element;
this.values[elementIndex] = parent;
elementIndex = parentIndex;
}
}
dequeue() {
const min = this.values[0];
const end = this.values.pop();
if (this.values.length > 0) {
this.values[0] = end;
this.trickleDown();
}
return min;
}
trickleDown() {
const element = this.values[0];
let index = 0;
const length = this.values.length;
while (true) {
let leftChildIndex = index * 2 + 1;
let rightChildIndex = leftChildIndex + 1;
let swapIndex = null;
let leftChild, rightChild;
if (leftChildIndex < length) {
leftChild = this.values[leftChildIndex];
if (leftChild.priority < element.priority)
swapIndex = leftChildIndex;
}
if (rightChildIndex < length) {
rightChild = this.values[rightChildIndex];
if (
(swapIndex && rightChild.priority < leftChild.priority) ||
(!swapIndex && rightChild.priority < element.priority)
)
swapIndex = rightChildIndex;
}
if (swapIndex === null) break;
this.values[index] = this.values[swapIndex];
this.values[swapIndex] = element;
index = swapIndex;
}
}
}
const q = new PriorityQueue();
q.enqueue('cold', 5);
q.enqueue('shot', 2);
q.enqueue('fever', 3);
q.enqueue('not-breathing', 1);
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());