如何在具有7个数字的简单基本Java伪代码中初始化堆数据结构?
答案 0 :(得分:1)
如果您想自己动手而不使用Java的PriorityQueue,那么您必须将所有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);
}
}
在寻找任何物品中最伟大的孩子时,你必须记住,一个或两个孩子可能在你的阵列之外。在这种情况下,您当然不必考虑它。
答案 1 :(得分:0)
使用PriorityQueue。它以Heap DS实现。
然后简单地使用queue.add(yourObject);
添加默认情况下,它使用自然排序,如果您还需要其他任何内容,则可以使用自己的Comparator。