[英]Max-heap implementation
下面是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
請告訴我有什么問題?
該消息告訴您究竟出了什么問題。 您尚未實施任何檢查來停止遞歸。 一個智能編譯器。
max_heap
函數沒有基本情況,即return語句。 你只是遞歸地調用函數,但從不說何時打破另一個對max_heap
連續調用。
此外,在您的示例中,您只是在不滿足任何條件的情況下調用該函數。 通常在滿足案例時完成或不完成遞歸。
請告訴我有什么問題?
我看到的另一個問題是數組x的大小是10.但是用於設置值的索引是1-10。
放
max_heap(x,largest,size);
在最后一次檢查中,像這樣:
if (largest!=i)
{
int s=x[i];
x[i]=x[largest];
x[largest]=s;
max_heap(x,largest,size);
}
你完成了!
您的代碼還有許多其他問題,但要回答您的具體問題,上面的更改就行了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.