简体   繁体   中英

Max-heap implementation

Following code for max-heap implementation

#include<iostream>
#include<math.h>
using namespace std;
#define  maxn 1000
int x[maxn];

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

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

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

}
void  max_heap(int x[],int i,int size){
    int largest;
    int l=left(i);
    int r=right(i);

    if (l<=size &&  x[l]>x[i]){
        largest=l;
    }
    else
    {
        largest=i;
    }
    if (r<=size && x[r]>x[largest]){
    largest=r;
    }
    if (largest!=i)  { int s=x[i];x[i]=x[largest];x[largest]=s;}
    max_heap(x,largest,size);
}




int main(){

 x[1]=16;
 x[2]=4;
 x[3]=10;
 x[4]=14;
 x[5]=7;
 x[6]=9;
 x[7]=3;
 x[8]=2;
 x[9]=8;
 x[10]=1;
  int size=10;
  max_heap(x,2,size);
   for (int i=1;i<=10;i++)
       cout<<x[i]<<"  ";






    return 0;
}

When I run it, it writes such kind of warning:

1>c:\users\datuashvili\documents\visual studio 2010\projects\heap_property\heap_property\heap_property.cpp(36): warning C4717: 'max_heap' : recursive on all control paths, function will cause runtime stack overflow

Please tell me what is wrong?

The message tells you exactly what's wrong. You haven't implemented any checks to stop the recursion. One smart compiler.

max_heap function doesn't have base case, ie, a return statement. You are just recursively calling the function but never saying when to break another successive call to the max_heap .

Also, in your example you are just calling the function with out satisfying any condition. Usually recursion is done or not done when a case is satisfied.

please tell me what is wrong?

Another problem that I see is that the size of your array x is 10. But the indices that you are using to set values are 1-10.

Put

max_heap(x,largest,size);

inside last check, like this:

if (largest!=i)  
{ 
    int s=x[i];
    x[i]=x[largest];
    x[largest]=s;
    max_heap(x,largest,size);
}

and you're done!

There are many other problems with your code, but to answer your specific question, above change would do!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM