最大堆实现

时间:2011-10-19 13:12:38

标签: c++ data-structures

遵循最大堆实现的代码

#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

请告诉我有什么问题?

4 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分:4)

max_heap函数没有基本情况,即返回语句。你只是递归地调用函数,但从不说何时打破另一个对max_heap的连续调用。

此外,在您的示例中,您只是在不满足任何条件的情况下调用该函数。通常在满足案例时完成或不完成递归。

答案 2 :(得分:0)

  请告诉我有什么问题?

我看到的另一个问题是数组x的大小是10.但是用于设置值的索引是1-10。

答案 3 :(得分:0)

max_heap(x,largest,size);

在最后一次检查中,像这样:

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

你已经完成了!

您的代码还有许多其他问题,但要回答您的具体问题,上述更改就可以了!

相关问题