upheap方法的递归函数(如何将这种非递归方法写入递归方法)

时间:2016-04-07 12:43:46

标签: java algorithm recursion heap

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

1 个答案:

答案 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
}