我正在尝试构建一个最小堆,但我没有得到正确的结果。我不确定可能出了什么问题。
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);
}
谢谢