最大堆实现

dat*_*ili 3 c++ data-structures

下面是max-heap实现的代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,会写出这样的警告:

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
Run Code Online (Sandbox Code Playgroud)

请告诉我有什么问题?

zvr*_*rba 17

该消息告诉您究竟出了什么问题.您尚未实施任何检查来停止递归.一个智能编译器.


Mah*_*esh 5

max_heap函数没有基本情况,即 return 语句。您只是递归调用该函数,但从未说明何时中断对max_heap.

另外,在您的示例中,您只是调用该函数而不满足任何条件。通常当情况满足时进行或不进行递归。