2011-12-29 8 views
-3

シンプルな基本的なJava疑似コードでヒープデータ構造を7つの数値で初期化するにはどうすればよいですか?ヒープデータ構造の初期化java

+3

Java擬似コードとは何ですか? Javaコードまたは擬似コードが必要ですか?これまでに何を試してみましたか?これは宿題ですか?その後、宿題にタグを付けます。 – taskinoor

答えて

1

あなたはJavaの優先度つきキューを使用して、それを自分でやるとしないようにしたいならば、あなたは彼らがヒープのプロパティを守るように、適切な場所で、すべてのX項目を配置する必要があります:

//This will switch the current item with it's greatest child, if this child is 
//larger than the current item itself. 
private void percolateDown(int i){ 
    //Get n's greatest child. The two children are at position 2i+1 and 2i+2 
    int n = getGreatestChild(i); 

    //Don't do anything if the greater child is smaller or equal to the parent 
    if(yourNumbersArray[n] <= yourNumbersArray[i]) 
     return; 

    //Now switch the parent with the greatest child 

    //Make sure that the newly placed item is at the right spot by percolating it again. 
    percolateDown(n); 
} 

private void initialize(){ 
    //Call the percolateDown() function for all items of your array. 
    //Due to the heap nature you can leave out the second half, though. 
    int mid = yourNumbersArray.length/2; 

//Start in the middle and work your way towards the front. 
//This way you'll first sort the lowest level of your heap, then the second lowest, and so on. 
    for(; mid>=0; --mid){ 
     percolateDown(mid); 
    } 
} 

任意の項目の最大の子を探して一方または両方の子供があなたの配列の外にいる可能性があることを覚えておく必要があります。この場合、もちろんそれを考慮する必要はありません。

0

PriorityQueue。ヒープDSとして実装されています。

次に、単にqueue.add(yourObject)を使用して追加します。

デフォルトでは自然順序付けが使用されます。他にも独自のものを使用する場合は、Comparatorを使用します。

関連する問題