0

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

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
  • Do you use 0-based indices? If it is the case, the indices of children should be 2 * i + 1 and 2 * i + 2, respectively(and the parent should be (i - 1) / 2). – kraskevich Jan 22 '15 at 23:55
  • @ILoveCoding That worked! If you post the answer, I'll accept it. Thank you – Luis Lavieri Jan 22 '15 at 23:59

1 Answers1

2

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).

kraskevich
  • 18,368
  • 4
  • 33
  • 45