0
我已經通過eloquentjavascript網站學習JavaScript,來到一些代碼,我似乎無法理解:二元堆 - 爲什麼remove函數需要調用bubbleUp方法?
remove: function(node) {
var length = this.content.length;
// To remove a value, we must search through the array to find
// it.
for (var i = 0; i < length; i++) {
if (this.content[i] != node) continue;
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
// If the element we popped was the one we needed to remove,
// we're done.
if (i == length - 1) break;
// Otherwise, we replace the removed element with the popped
// one, and allow it to float up or sink down as appropriate.
this.content[i] = end;
this.bubbleUp(i);
this.sinkDown(i);
break;
}
},
我的問題是 - 爲什麼這個功能需要調用bubbleUp()? 如果end是二進制堆的最後一個值,並且通過push()方法添加到堆中的每個值調用bubbleUp時,怎麼可能最終值的分數低於i的值?我對數據結構很陌生,似乎無法弄清楚這一點。
當我看到您的示例樹時,它非常有意義,謝謝。 (儘管如果你的例子在左邊的右邊高值處理了小堆和低值,我會理解得更快。) – mbarton
@mbarton:更好? :) – cHao
我認爲對於也有同樣問題的其他人可能更容易。謝謝 :) – mbarton