-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMinHeapWithArray.js
92 lines (79 loc) · 2.03 KB
/
MinHeapWithArray.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
90
91
92
class MinHeap {
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, startIdx) {
let idx = startIdx !== undefined ? startIdx : array.length - 1;
let parentIdx = Math.floor((idx - 1) / 2);
while (parentIdx >= 0) {
if (array[idx][1] < array[parentIdx][1]) {
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, this.heap.length - 1);
}
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][1] < array[leftChildIdx][1]
) {
idxToSwap = rightChildIdx;
}
if (array[idxToSwap][1] < array[idx][1]) {
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;
}
delete(value) {
const index = this.heap.indexOf(value);
if (index === -1) return false;
const lastIdx = this.heap.length - 1;
this.swap(this.heap, index, lastIdx);
this.heap.pop();
if (index < this.heap.length) {
this.siftUp(this.heap, index);
this.siftDown(this.heap, index, this.heap.length - 1);
}
return true;
}
swap(array, i, j) {
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}