2012-04-27 4 views
0

私の挿入メソッドに問題があります。スワップする必要のある数値を追加すると、範囲外のインデックスが取得されます。ここで:Collections.swap(table、table.get(parent)、table.get(child));これが私がヒープに追加する方法です。 tHeap.insert(14);助けてくれてありがとう。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)); 

    } 

} 
    } 
+1

あなたは 'Collections.swap(table、parent、child);'を意味しますか? 'ArrayList.get'はインデックス(http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#get%28int%29)'コレクションの要素を返します。 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'を更新したいと思うかもしれません。私はこのコンピュータ上で、今は何かをテストするための日食はありません。 –

+0

私はそれを逃したと思います。ありがとうございます – Sloshy

+0

@WordsLikeJared私たちは未回答のリストからこれを得ることができるように、あなたは以下の答えとしてその解決策を投稿できますか?ありがとう。 –

答えて

0

Collections.swap(table, parent, child);と思いますか? ArrayList.getは、インデックス(Java ArrayList API)の要素を返します。Collections.swapは、インデックス(Java Collections API)で要素をスワップします。インデックスに値を渡すのではなく、インデックスに値を渡したいとします。また、あなたのwhileループでは、子と親を更新したいと思うかもしれません。

関連する問題