Search code examples
javaheapmin-heap

Heapify is giving me an incorrect output for a min-heap


I'm trying to build a min-heap, but I am failing to get the correct results. I am not sure what might be wrong.

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

As you can see, 90 should not be the right child of 97...

Here is my code:

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);
    }
}

This is how I build the min-heap:

heapSize = nRandomNumbers.length;

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

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

Thanks


Solution

  • If you use zero-based indices, the indices of children should be 2 * i + 1 and 2 * i + 2(and the index of the parent should be (i - 1) / 2).