下面是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;
}当我运行它时,它会写下这样的警告:
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请告诉我出了什么问题?
发布于 2011-10-19 21:17:28
这条消息确切地告诉您出了什么问题。您还没有实现任何检查来停止递归。一个智能编译器。
发布于 2011-10-19 21:17:16
max_heap函数没有基本情况,即返回语句。您只是递归地调用函数,但从未说明何时中断对max_heap的另一个连续调用。
此外,在您的示例中,您只是在不满足任何条件的情况下调用函数。通常情况下,当条件满足时,递归被完成或不被完成。
发布于 2011-10-19 21:41:03
请告诉我出了什么问题?
我看到的另一个问题是数组x的大小是10,但是你用来设置值的索引是1-10。
https://stackoverflow.com/questions/7821857
复制相似问题