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
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.