-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriorityQueue.js
80 lines (65 loc) · 1.68 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
/**
* 01/01/2022 by Cheng(ccwukong)
*
* In this implementation, I'll implement the PriorityQueue using MinHeap,
* means that, an item has higher prority will have smaller weight
*
* Heap has to be a complete binary tree
*
* Time complexity: build queue O(nlogn), enqueue O(logn), dequeue O(logn), peek O(1)
* Space complexity: O(n)
*/
class PriorityQueue {
constructor(arr) {
this.heap = arr;
this.end = arr.length - 1;
for (let i = this.end; i >= 0; i--) {
this.heapify(i);
}
}
heapify(idx) {
if (idx > this.end) return;
let left = idx * 2 + 1;
let right = idx * 2 + 2;
let smallest = idx;
if (left <= this.end && this.heap[left] < this.heap[smallest]) {
smallest = left;
}
if (right <= this.end && this.heap[right] < this.heap[smallest]) {
smallest = right;
}
if (idx !== smallest) {
let tmp = this.heap[idx];
this.heap[idx] = this.heap[smallest];
this.heap[smallest] = tmp;
this.heapify(smallest);
}
}
enqueue(n) {
this.heap = [
...this.heap.slice(0, this.end + 1),
n,
...this.heap.slice(this.end + 1),
];
this.end++;
let curr = this.end;
while (curr > 0 && this.heap[curr] < this.heap[parseInt((curr - 1) / 2)]) {
let tmp = this.heap[curr];
this.heap[curr] = this.heap[parseInt((curr - 1) / 2)];
this.heap[parseInt((curr - 1) / 2)] = tmp;
curr = parseInt((curr - 1) / 2);
}
}
dequeue() {
let tmp = this.heap[0];
this.heap[0] = this.heap[this.end];
this.heap[this.end] = tmp;
this.end--;
this.heapify(0);
return tmp;
}
peek() {
return this.heap[0];
}
}
module.exports = PriorityQueue;