我正在尝试建立最小堆,但是无法获得正确的结果。我不确定可能有什么问题。

input = 209 97 298 54 110 27 250 455 139 181 446 206 478 90 88

output = 27 54 97 88 110 206 90 209 139 181 446 298 478 250 455

如您所见,90不应是97的正确子代...

这是我的代码:

static void Heapify( int nIndex )
{
    int nLeftIndex = GetLeft(nIndex); //2*nIndex
    int nRightIndex = GetRight(nIndex);//2*nIndex+1
    int nSmallest;

    if(heapSize > nLeftIndex && nHeap[nLeftIndex] < nHeap[nIndex])
        nSmallest = nLeftIndex;
    else
        nSmallest = nIndex;

    if(heapSize > nRightIndex && nHeap[nRightIndex] < nHeap[nSmallest])
        nSmallest = nRightIndex;

    if(nSmallest != nIndex){
        swap(nHeap, nIndex, nSmallest);
        Heapify(nSmallest);
    }
}


这就是我构建min-heap的方式:

heapSize = nRandomNumbers.length;

//GetParentIndex() returns n / 2 and HeapSize = 15

for(int i = GetParentIndex(heapSize - 1); i >= 0; i--){
    Heapify(i);
}


谢谢

最佳答案

如果使用从零开始的索引,则子级的索引应为2 * i + 1和2 * i + 2(父级的索引应为(i-1)/ 2)。

关于java - Heapify给我的最小堆输出不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28100756/

10-12 22:01