我正在尝试构建一个min-heap,但是我没有得到正确的结果。我不确定会出现什么问题。
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);
}
由于
答案 0 :(得分:2)
如果使用从零开始的索引,则子项的索引应为2 * i + 1和2 * i + 2(并且父项的索引应为(i-1)/ 2)。