为什么这段代码应该正确地陷入无限循环,但为什么正确?

时间:2019-07-09 14:04:56

标签: binary-heap

一段时间以来,我一直对此代码有疑问。函数的递归调用的位置似乎不正确。

我尝试运行代码,是的,它确实遇到了无限循环。

// I DEFINE HEAP STRUCTURE AS :
struct heap_array
{
  int *array;  // heap implementation using arrays(note : heap is atype of a tree).

  int capacity;  // how much the heap can hold.
  int size;   //how much size is currently occupied.

void MaxHeapify(struct heap_array *h,int loc)  // note : loc is the location of element to be PERCOLATED DOWN.
{
  int left,right,max_loc=loc;
  left=left_loc_child(h,loc);
  right=right_loc_child(h,loc);

  if(left !=-1 && h->array[left]>h->array[loc])
  {
    max_loc=left;
  }

  if(right!=-1 && h->array[right]>h->array[max_loc])
  {
    max_loc=right;
  }

  if(max_loc!=loc)  //i.e. if changes were made:
  {
    //swap the element at max_loc and loc
    int temp=h->array[max_loc];
    h->array[max_loc]=h->array[loc];
    h->array[loc]=temp;


  }
    MaxHeapify(h,max_loc); // <-- i feel that this recursive call is misplaced. I have seen the exact same code in almost all the online videos and some books i referred to. ALSO I THINK THAT THE CALL SHOULD BE MADE WITHIN THE SCOPE OF condition if(max_loc!=loc).
    //if no changes made, end the func right there.
}

1 个答案:

答案 0 :(得分:0)

在当前的实现中,您似乎没有停止递归的基本条件。

请记住,you need a base case in a recursive function(在这种情况下,是您的MaxHeapify函数),看起来好像没有一个。

Here is an example of MaxHeap可能很有用

// A recursive function to max heapify the given 
    // subtree. This function assumes that the left and 
    // right subtrees are already heapified, we only need 
    // to fix the root. 
    private void maxHeapify(int pos) 
    { 
        if (isLeaf(pos)) 
            return; 

        if (Heap[pos] < Heap[leftChild(pos)] ||  
            Heap[pos] < Heap[rightChild(pos)]) { 

            if (Heap[leftChild(pos)] > Heap[rightChild(pos)]) { 
                swap(pos, leftChild(pos)); 
                maxHeapify(leftChild(pos)); 
            } 
            else { 
                swap(pos, rightChild(pos)); 
                maxHeapify(rightChild(pos)); 
            } 
        } 
    } 

在这里,您可以看到以下情况的基本情况:

    if (isLeaf(pos)) 
        return; 

您需要在递归函数中添加一个基本案例。