我看到將項目添加到二進制堆的奇怪行爲。我添加三個值:20,31,12
。當我檢查數組中的項目時,現在有5個值:12,20,20,31,12
。我無法弄清楚重複來自哪裏。它爲什麼複製項目?堆插入方法中的雙項目
添加項目:
public void add(int x){
int hole = heap.size();
heap.add(hole, x);
bubbleUp(hole);
}
的bubbleup
方法:
private void bubbleUp(int child) {
int parent;
Bid tmp;
if (child != 0) {
parent = (child-1)/2;
if (heap.get(parent).compareTo(heap.get(child))) {
tmp = heap.get(parent);
heap.add(parent, heap.get(child));
heap.add(child, tmp);
bubbleUp(parent);
}
}
}
感謝您的幫助!我感到羞愧......我應該發現這個錯誤。那麼我不會再做一次! ;) 再次感謝! – user1501127 2013-04-30 13:53:56