max_heapify procedure on heap

后端 未结 5 640
無奈伤痛
無奈伤痛 2021-01-22 02:27

i have these procedure

#include 
using namespace std;

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

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

int right(i         


        
相关标签:
5条回答
  • 2021-01-22 03:13

    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.

    0 讨论(0)
  • 2021-01-22 03:17

    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.

    0 讨论(0)
  • 2021-01-22 03:27

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

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

    0 讨论(0)
  • 2021-01-22 03:28

    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.

    0 讨论(0)
  • 2021-01-22 03:31

    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.

    0 讨论(0)
提交回复
热议问题