upheap 方法的递归函数(我如何将这个非递归方法写成递归的)

recursive function for upheap method(how can i write this non-recursive method into recursive)

 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.i 尝试了很多网站,但我没有得到答案

重点是将 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
}