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
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
.
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.
Here is the version I wrote, you can take a look.
http://code.google.com/p/clibutils/source/browse/src/c_heap.c
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.
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.