-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax_heap.js
69 lines (53 loc) · 1.52 KB
/
max_heap.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
class MaxHeap {
constructor() {
this.array = [null];
}
getParent(idx) {
return Math.floor(idx / 2);
}
getLeftChild(idx) {
return idx * 2;
}
getRightChild(idx) {
return (idx * 2) + 1;
}
siftUp(idx) {
if (idx === 1) return;
const parentIdx = this.getParent(idx);
if (this.array[parentIdx] < this.array[idx]) {
[ this.array[idx], this.array[parentIdx] ] = [ this.array[parentIdx], this.array[idx] ];
this.siftUp(parentIdx);
}
}
insert(val) {
this.array.push(val);
this.siftUp(this.array.length - 1);
}
siftDown(idx) {
if (idx === this.array.length - 1) return;
const leftChildIdx = this.getLeftChild(idx);
const rightChildIdx = this.getRightChild(idx);
const leftVal = this.array[leftChildIdx] || -Infinity;
const rightVal = this.array[rightChildIdx] || -Infinity;
if (leftVal > this.array[idx] || rightVal > this.array[idx]) {
if (leftVal > rightVal) {
[ this.array[idx], this.array[leftChildIdx] ] = [ this.array[leftChildIdx], this.array[idx] ];
this.siftDown(leftChildIdx);
} else {
[ this.array[idx], this.array[rightChildIdx] ] = [ this.array[rightChildIdx], this.array[idx] ];
this.siftDown(rightChildIdx);
}
}
}
deleteMax() {
if (this.array.length === 1) return null;
if (this.array.length === 2) return this.array.pop();
const max = this.array[1];
this.array[1] = this.array.pop();
this.siftDown(1);
return max;
}
}
module.exports = {
MaxHeap
};