protected void up-heap(int j) {
while (j > 1) { // continue until reaching root (or break)
int p = parent(j);
if (compare(heap.get(j), heap.get(p)) >= 1) break; // heap property verified
swap(j, p);
j = p; // continue from the parent's location
}}
如何使用java.i将这个非递归代码写入recursive我没有得到如何将其转换为recursive.i尝试了很多网站,但我没有得到答案
答案 0 :(得分:2)
重点是将while
循环重写为递归方法调用。这很简单:
protected void upHeap(int j) {
if (j <= 1) //this handles the condition of the original while loop
return;
int p = parent(j);
if (compare(heap.get(j), heap.get(p)) >= 1)
return; // this handles the break from the while loop
swap(j, p);
upHeap(p); // the recursive method call, replacing j with p
}