max_heapify procedure on heap

谁都会走 提交于 2019-12-20 03:06:50

问题


i have these procedure

#include <iostream>
using namespace std;

int parent(int i ){
    return  i/2;
}

int left(int i ){
    return  2*i;
}

int right(int i){
    return 2*i+1;    
}

int a[]={ 27,17,3,16,10,1,5,7,12,4,8,9,10};
int n=sizeof(a)/sizeof(int);

void max_Heapify(int i){
    int largest=0;
    int l=left(i);
    int r=right(i);
    if(l<=n && a[l]>a[i]){
        largest=l;
    }
    else{
        largest=i;
    }
    if(r< n && a[r]>a[largest]){
        largest=r;
    }
    if (largest!=i){
        int t=a[i];
        a[i]=a[largest];
        a[largest]=t;
    }
    max_Heapify(largest);
}

int main(){
     max_Heapify(2);
     for (int i=0;i<n;i++){
         cout<<a[i]<<"  ";
     }    
return 0;
}

when i run it compiles fine but after run stops ubnormaly it's running why? please help look at this code

Max-Heapify[2](A, i):
 left ← 2i
 right ← 2i + 1
 largest ← i
 if left ≤ heap-length[A] and A[left] > A[i] then:
 largest ← left
 if right ≤ heap-length[A] and A[right] > A[largest] then:
 largest ← right
 if largest ≠ i then:
 swap A[i] ↔ A[largest]
 Max-Heapify(A, largest)

From Wikipedia.


回答1:


You translated the pseudo-code from the Wikipedia article into C++ code, but you accidentally altered the logic. In the Wikipedia article, you'll notice that the recursion only happens conditionally: that is, if largest ≠ i

if largest ≠ i then:
    swap A[i] ↔ A[largest]
    Max-Heapify(A, largest)

Translated into C++, this should read something like:

if (largest != i) {
  swap(a[i], a[largest]);
  Max_Heapify(largest);
}

Again, notice that the recursive call to Max_Heapify only happens conditionally, when largest != i. In your code, you recursively call Max_Heapify unconditionally, meaning that you keep recursing no matter what. So obviously your program is going to crash with a stack overflow. Unlike iteration, you can't recurse infinitely because you quickly run out of stack space.




回答2:


You don't have a base case to terminate the recursion, so I imagine you're eventually getting a stack overflow. Think about when you can tell that you're done so you can gracefully fall out of the function.




回答3:


Perhaps you shouldn't always call max_Heapify tail-recursively, but instead return when you've hit the bottom size of the sorting heap... What happens is that your program runs out of stack.

Also, check out std::swap.




回答4:


The function max_Heapify always recurses infinitely. You are seeing a stack overflow (small s, small o).

If you step through your code in the debugger, this sort of thing will quickly be obvious.




回答5:


Here is the version I wrote, you can take a look.

http://code.google.com/p/clibutils/source/browse/src/c_heap.c



来源:https://stackoverflow.com/questions/4185139/max-heapify-procedure-on-heap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!