-1

This code is given in the book "Introduction to Algorithms". For this I used 1 indexed array

#include <cstdlib>
#include <iostream>

using namespace std;
int n=6;
int x[1000];

void max_heapify(int a[],int i)
{
    int left=2*i;
    int right=2*i+1;
    int largest=i;
    if( left<=n && a[left]>a[largest]){
        largest=left;

    }
    if(right<=n &&  a[right]>a[largest])
    {
        largest=right;

    }
    if(largest!=i)
    {
        int t=a[i];
        a[i]=a[largest];
        a[largest]=t;

    }
    max_heapify(a,largest);
}
void max_heap(int a[])
{
    int heap_length=n;
    for(int i=n/2;i>=1;i--)
        max_heapify(a,i);

}
int main(int argc, char *argv[])
{
    for(int i=1;i<=n;i++)
        cin>>x[i];
    max_heap(x);
    cout<<endl;

    for(int i=1;i<=n;i++)
        cout<<x[i]<<"  ";
    // system("PAUSE");
    //return EXIT_SUCCESS;
    return 0;
}

For this input

1 5 7 8 3 9

on ideone.com it writes "time limit exceeded". I have tried the debugger in Visual Studio, with the following result

First-chance exception at 0x001c14d9 in max_heap.exe: 0xC00000FD: Stack overflow.
Unhandled exception at 0x001c14d9 in max_heap.exe: 0xC00000FD: Stack overflow.
First-chance exception at 0x001c14d9 in max_heap.exe: 0xC0000005: Access violation writing location 0x002c0ffc.
Unhandled exception at 0x001c14d9 in max_heap.exe: 0xC0000005: Access violation writing location 0x002c0ffc.
The program '[6044] max_heap.exe: Native' has exited with code -1073741819 (0xc0000005).

What is wrong?

Bart
  • 19,692
  • 7
  • 68
  • 77
  • Have you tried debugging? I mean really debugging, not just running in a debug mode? Step by step operation etc. Your recursion is probably too deep, debug your recursive function to find out why it doesn't stop when you expect it to. – littleadv Mar 17 '12 at 21:46

1 Answers1

6

Your max_heapify will always end up in another recursion. There is no termination happening in any of the control paths. This causes your stack overflow.

Bart
  • 19,692
  • 7
  • 68
  • 77
  • but on wikipedia it is described so –  Mar 17 '12 at 21:56
  • I assume you mean [here](http://en.wikipedia.org/wiki/Binary_heap)? Then no, it's not. There the recursive call only happens as part of the last if statement. In your code it always happens. – Bart Mar 17 '12 at 21:57
  • because it is pseudo code,i could not understand when is end point of if statment –  Mar 17 '12 at 22:03
  • one question esle,during the algorithm of heapsort,i dont understand what mmeaning has heap_size? –  Mar 17 '12 at 22:18
  • `heap_size`? I don't see where you get that from. Anyway, that is a different question. – Bart Mar 17 '12 at 22:31