Hello! I've been working on implementing a min heap in JavaScript and I have a question about the removeMin algorithm. I am using an array to store the heap internally. When percolating downwards, I am currently using the condition 2 * k <= this.size as the stopping point. However, it doesn't feel quite right to me. Do you have any suggestions for a better stopping condition? Thank you in advance for your help!
this.removeMin = function () {
//replace root with last element and percolate downwards
var min = this._heap[1],
k,
left,
right;
this._heap[1] = this._heap.pop();
this.size--;
k = 1;
while ( ( 2 * k ) <= this.size) {
left = 2 * k;
right = 2 * k + 1;
if (this._heap[k] > this._heap[left] && this._heap[k] > this._heap[right]) {
if (this._heap[left] <= this._heap[right]) {
swap(this._heap, k, left);
k = left;
} else {
swap(this._heap, k, right);
k = right;
}
} else if (this._heap[k] > this._heap[left]) {
swap(this._heap, k, left);
k = left;
} else {
swap(this._heap, k, right);
k = right;
}
}
return min;
};