The following is a recursive heapify function for an array based priority queue/binary heap.
Can anybody tell me why I'm going into an infinite recursion?
private static void heapify(int i){
if(i < b_heap.size()/2){
int left = i * 2;
int right = left++;
if(b_heap.get(i).getP() > b_heap.get(left).getP()){
swap(i,left);
}
if(b_heap.get(i).getP() > b_heap.get(right).getP()){
swap(i,right);
}
heapify(i++);
heapify(i+2);
}
else{
return;
}
}
ok so I fixed the infinite loop, but the function still doesn't heapify correctly.
here is the new code,
private static void heapify(int i){
DecimalFormat df = new DecimalFormat("0.00");
if(i < b_heap.size()/2){
int left = i * 2;
int right = i * 2 +1;
if(b_heap.get(i).getP() > b_heap.get(left).getP()){
swap(i,left);
}
if(b_heap.get(i).getP() > b_heap.get(right).getP()){
swap(i,right);
}
i++;
heapify(i);
}
else{
return;
}
}
i++
: this gives heapifyi
and then increments it.left++
. I think you need to read up on what the++
operator does. It is NOT the same thing as+1
.