I am not sure why my heap method is not printing the heap in the correct order. Can someone tell me what am I doing wrong here?
Here is my getHeap method:
public static String getHeap(ArrayBasedList<Edge> edgeList)
{
// Build the heap
insert(new Edge(-1,-1,-1));
for(int i = 1; i < edgeList.size(); i++)
{
// Insert into the heap
insert(edgeList.get(i));
}
// Print the heap
String output="";
for(int i = 1; i < edgeList.size(); i++)
{
//System.out.printf("%4d%5d\n", heap[i].getVertex1(), heap[i].getVertex2());
output+=String.format("%4d%5d\n", heap[i].getVertex1(), heap[i].getVertex2());
}
return output;
}
and here are my insert and upHeap methods:
public static void insert(Edge e)
{
heap[edgeCount] = e;
edgeCount++;
upHeap(edgeCount - 1);
}
public static void upHeap(int pos){
if(pos > 0){
if(heap[(pos-1)/2].getWeight() > heap[pos].getWeight()){
/** Temporary edge for swapping */
Edge temp = heap[pos];
heap[pos] = heap[(pos-1)/2];
heap[(pos-1)/2] = temp;
upHeap((pos-1)/2);
}
}
}
and here is the print out of the edges of my heap :
0 1
1 2
2 3
1 3
0 3
but it is incorrect. the correct result is as follows:
0 1
0 2
1 2
2 3
1 3
0 3
what am I doing wrong here? would greatly appreciate any thoughts.. i am at a loss here.