0
我有我的插入方法的問題。當我去添加一個需要交換的數字時,我得到一個索引越界異常。這裏:Collections.swap(table,table.get(parent),table.get(child));這就是我加入堆的方式。 tHeap.insert(14);謝謝你的幫助。實現一個堆unsan任何arraylist
public class Heap {
private ArrayList<Integer> table;
public Heap() {
table = new ArrayList<Integer>();
}
public void insert(Integer toInsert) {
table.add(toInsert);
int child = table.size() - 1;
int parent = (child - 1)/2;
//TextIO.putln("1 " + parent + " " + toInsert + " " + child);
while (parent >= 0 && table.get(parent) > table.get(child)) {
TextIO.putln("Swapping: " + parent + " Parent for Child: " + child);
Collections.swap(table, table.get(parent), table.get(child));
}
}
public void printTable() {
for (int i = 0; i < table.size(); i++) {
TextIO.putln("Index: " + i + " Data: " + table.get(i));
}
}
}
你的意思是'Collections.swap(table,parent,child);'? 'ArrayList.get'將在索引處(http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#get%28int%29)'Collections'返回元素。 swap'在索引處交換元素(http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int %29)。你想要通過指數,而不是指數的價值。此外,我認爲在你的while循環中你可能想要更新'child'和'parent'。不過,我現在沒有在這臺電腦上進行日食測試。 – 2012-04-27 16:29:27
我不相信我錯過了。謝謝 – Sloshy 2012-04-27 16:36:23
@WordsLikeJared您可以將該解決方案作爲下面的答案發布,以便我們可以從未答覆的列表中獲得此答案嗎?謝謝。 – 2013-01-17 14:23:13