-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_heap.js
More file actions
63 lines (54 loc) · 1.43 KB
/
max_heap.js
File metadata and controls
63 lines (54 loc) · 1.43 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
class MaxHeap {
constructor() {
this.heap = [null];
}
insert(node) {
this.heap.push(node);
if (this.heap.length > 1) {
let current = this.heap.length - 1;
while (
current > 1 &&
this.heap[Math.floor(current / 2)] < this.heap[current]
) {
[this.heap[Math.floor(current / 2)], this.heap[current]] = [
this.heap[current],
this.heap[Math.floor(current / 2)],
];
current = Math.floor(current / 2);
}
}
}
remove() {
let small = this.heap[1];
let current = this.heap.length - 1;
// root remove
if (this.heap.lenght > 2) {
this.heap[1] = this.heap[current];
this.heap.splice(current);
if (this.heap.length === 3) {
if (this.heap[1] < this.heap[2]) {
[this.heap[1], this.heap[2]] = [this.heap[2], this.heap[1]];
}
return small;
}
let i = 1;
let left = 2 * i;
let right = 2 * i + 1;
while (
this.heap[i] <= this.heap[left] ||
this.heap[i] <= this.heap[right]
) {
if (this.heap[left] > this.heap[right]) {
[this.heap[i], this.heap[left]] = [this.heap[left], this.heap[i]];
i = left;
} else {
[this.heap[i], this.heap[right]] = [this.heap[right], this.heap[i]];
i = right;
}
left = 2 * i;
right = 2 * i + 1;
}
}
}
}
const min = new MinHeap();