I am preparing for a data structures and algorithms final exam. I am trying to work through all of the data structures we have learnt this semester and program them by my self to help prepare me for the final. I am working on the max heap right now which includes a inserting (with a heapify) and a retrieve max. I am stuck on the heapifying/swapping of the parent and the child. It seems that the heapify is not working as I get back an array in the order of the way the numbers were inserted. Here is what I have so far.
private int getLeftChildIndex(int index)
{
return (2*index + 1);
}
private int getLeftChildValue(int index)
{
return heap[2*index + 1];
}
private int getRightChildIndex(int index)
{
return (2*index + 2);
}
private int getRightChildValue(int index)
{
return heap[2*index + 2];
}
private int getParentIndex(int index)
{
return ((int) Math.ceil((index - 2)/2));
}
private void swap(int child, int parent)
{
int temp = heap[parent];
heap[parent] = heap[child];
heap[child] = temp;
}
private void insert(int num)
{
heap[heapSize] = num;
heapSize++;
int index = heapSize - 1;
while (getParentIndex(index) > 0 && heap[index] > heap[getParentIndex(index)])
{
swap(index, getParentIndex(index));
index = getParentIndex(index);
}
}
public static void main(String[] args)
{
HeapTest heap = new HeapTest();
heap.insert(15);
heap.insert(5);
heap.insert(10);
heap.insert(30);
}
which just gives an array of the form [15,5,10,30] for example. This array for a max heap should be of the form [30,15,10,5]
Im expecting this: [15,5,10,30] -> [15,30,10,5] -> [30,15,10,5]
Could any one provide some insight as to why the heapify part of insert is not working?
Thanks!!
There are a couple of issues I can see.
consider what
Math.ceil((index - 2)/2)
would return for index 3. This would return 0 rather than 1 because the/2
is an integer operation. Changing that to/2.0
will fix it. Or even simpler would be to make use of integer arithmetic with(index - 1) / 2
which is clearer and more efficient.getParentIndex(index) > 0
means that you are ignoring the root node at index 0 - currently your code will never swap that item. changing to>=
will fix it.There could well be other issues but those are 2 I can see by inspection. Either unit testing or interactive debugging would have uncovered those issues.