0
嘿我試圖在JavaScript中實現一個小堆,但我有一個關於刪除最小的算法的問題。我使用數組來表示堆內部。當我向下滲透時,停止條件應該是什麼?在我的代碼中,我使用了2 * k < = this.size,所以它可能會傳遞到最後一個元素,但它不會覺得「正確」,是否有更好的停止條件?提前致謝!在JavaScript中的最小堆
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;
};
爲什麼?該索引基本上每一步都會加倍,所以你應該在O(log n) –