배열의 첫번째 값은 비워둔다
const heap = [null];
left child index = parent 2
right child index = parent 2 + 1
parent index = Math.floor(child index / 2)
[a, b] = [b, a];
class minHeap {
constructor() {
this.heap = [null];
}
getMin() {
return this.heap[1];
}
swap(a, b) {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
}
getSize() {
return this.heap.length - 1;
}
insert(value) {
this.heap.push(value);
let currIdx = this.heap.length - 1;
let parentIdx = Math.floor(currIdx / 2);
while(this.heap[parentIdx] > this.heap[currIdx] && currIdx > 1) {
// swap
let temp = this.heap[parentIdx];
this.heap[parentIdx] = this.heap[currIdx];
this.heap[currIdx] = temp;
//
[this.heap[parentIdx], this.heap[currIdx]] = [this.heap[currIdx], this.heap[parentIdx]]
currIdx = parentIdx;
parentIdx = Math.floor(currIdx / 2);
}
}
delete(value) {
const min = this.heap[1]; // smallest element is root
// when there are more 2 elements in the array, put the right most at the first root.
if(this.heap.length <= 2) this.heap = [null];
else this.heap[1] = this.heap.pop();
let currIdx = 1;
let leftIdx = currIdx * 2;
let rightIdx = currIdx * 2 + 1;
// if there's no left, right doesn't exist too.
if(!this.heap[leftIdx]) return min;
// left && !right
if(!this.heap[rightIdx]) {
if(this.heap[currIdx] < this.heap[leftIdx]) {
[this.heap[currIdx], this.heap[leftIdx]] = [this.heap[leftIdx], this.heap[currIdx]];
}
return min;
}
// both left, right exist
while(this.heap[currIdx] < this.heap[leftIdx] || this.heap[currIdx] < this.heap[rightIdx]) {
const minChildIdx = this.heap[leftIdx] < this.heap[rightIdx] ? leftIdx : rightIdx;
[this.heap[currIdx], this.heap[minChildIdx]] = [this.heap[minChildIdx], this.heap[currIdx]];
currIdx = minChildIdx;
leftIdx = currIdx * 2;
rigthIdx = curridx * 2 + 1;
}
}
}