-
Notifications
You must be signed in to change notification settings - Fork 1
/
MaxHeap.js
76 lines (67 loc) · 1.59 KB
/
MaxHeap.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
class MaxHeap {
constructor(array) {
this.heap = this.buildHeap(array);
}
getLength() {
return this.heap.length;
}
buildHeap(array) {
const firstParentIdx = Math.floor((array.length - 2) / 2);
for (let i = firstParentIdx; i >= 0; i--) {
this.siftDown(array, i, array.length - 1);
}
return array;
}
peek() {
return this.heap[0];
}
siftUp(array) {
let idx = array.length - 1;
let parentIdx = Math.floor((idx - 1) / 2);
while (parentIdx >= 0) {
if (array[idx] > array[parentIdx]) {
this.swap(array, idx, parentIdx);
idx = parentIdx;
parentIdx = Math.floor((idx - 1) / 2);
} else {
break;
}
}
}
insert(num) {
this.heap.push(num);
this.siftUp(this.heap);
}
siftDown(array, idx, endIdx) {
let leftChildIdx = idx * 2 + 1;
while (leftChildIdx <= endIdx) {
let idxToSwap = leftChildIdx;
let rightChildIdx = idx * 2 + 2;
if (
rightChildIdx <= endIdx &&
array[rightChildIdx] > array[leftChildIdx]
) {
idxToSwap = rightChildIdx;
}
if (array[idxToSwap] > array[idx]) {
this.swap(array, idxToSwap, idx);
idx = idxToSwap;
leftChildIdx = idx * 2 + 1;
} else {
break;
}
}
}
remove() {
const valueToRemove = this.heap[0];
this.swap(this.heap, 0, this.heap.length - 1);
this.heap.pop();
this.siftDown(this.heap, 0, this.heap.length - 1);
return valueToRemove;
}
swap(array, i, j) {
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}