以下是基于数组的优先级队列/二叉堆的递归 heapify 函数。
谁能告诉我为什么我要进入无限递归?
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;
}
}
好的,所以我修复了无限循环,但该函数仍然无法正确堆积。
这是新代码,
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;
}
}