Java Heapify为最小堆提供了不正确的输出
我正在尝试构建一个最小堆,但是没有得到正确的结果。我不确定可能出了什么问题Java Heapify为最小堆提供了不正确的输出,java,heap,min-heap,Java,Heap,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 = GetLe
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);
}
}
谢谢如果您使用基于零的索引,则子项的索引应为2*i+1和2*i+2(父项的索引应为(i-1)/2)。是否使用基于零的索引?如果是这样的话,子项的索引应该分别是2*i+1和2*i+2(父项应该是(i-1)/2)。@ILoveCoding成功了!如果你把答案贴出来,我会接受的。非常感谢。
heapSize = nRandomNumbers.length;
//GetParentIndex() returns n / 2 and HeapSize = 15
for(int i = GetParentIndex(heapSize - 1); i >= 0; i--){
Heapify(i);
}