Skip to content

Commit 58c5abf

Browse files
committed
add min-heap-construction question
1 parent 15a4565 commit 58c5abf

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

heaps/min-heap-construction.js

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class MinHeap {
2+
constructor(array) {
3+
this.heap = this.buildHeap(array);
4+
}
5+
6+
buildHeap(array) {
7+
const firstParentIdx = Math.floor((array.length - 2) / 2);
8+
for(let currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) {
9+
this.siftDown(currentIdx, array.length - 1, array);
10+
}
11+
return array;
12+
}
13+
14+
siftDown(currentIdx, endIdx, heap) {
15+
let childOneIdx = currentIdx * 2 + 1;
16+
while(childOneIdx <= endIdx) {
17+
const childTwoIdx = currentIdx * 2 + 2 <= endIdx ? currentIdx * 2 + 2 : -1;
18+
let idxToSwap;
19+
if(childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx]) {
20+
idxToSwap = childTwoIdx;
21+
} else {
22+
idxToSwap = childOneIdx;
23+
}
24+
if(heap[idxToSwap] < heap[currentIdx]) {
25+
this.swap(currentIdx, idxToSwap, heap);
26+
currentIdx = idxToSwap;
27+
childOneIdx = currentIdx * 2 + 1;
28+
} else {
29+
return;
30+
}
31+
}
32+
}
33+
34+
siftUp(currentIdx, heap) {
35+
let parentIdx = Math.floo((currentIdx - 1) / 2);
36+
while(currentIdx > 0 && heap[currentIdx] < heap[parentIdx]) {
37+
this.swap(currentIdx, parentIdx, heap);
38+
currentIdx = parentIdx;
39+
parentIdx = Math.floor((currentIdx - 1) / 2);
40+
}
41+
}
42+
43+
peek() {
44+
return this.heap[0];
45+
}
46+
47+
remove() {
48+
this.swap(0, this.heap.length - 1, this.heap);
49+
const valueToRemove = this.heap.pop();
50+
this.siftDown(0, this.heap.length - 1, this.heap);
51+
return valueToRemove;
52+
}
53+
54+
insert(value) {
55+
this.heap.push(value);
56+
this.siftUp(this.heap.length - 1, this.heap);
57+
}
58+
59+
swap(i, j, heap) {
60+
const temp = heap[j];
61+
heap[j] = heap[i];
62+
heap[i] = temp;
63+
}
64+
}
65+
66+
67+
const myHeap = new MinHeap([48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]);
68+
69+
console.log(myHeap.remove())

0 commit comments

Comments
 (0)