构建堆过程 [英] build heap procedure
本文介绍了构建堆过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
build heap procedure crash during it's worlking
#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){
bool s=true;
int largest;
for (int k=1;k<size/2;k++){
if(x[k]< x[2*k] || x[k]<x[2*k+1]){
s=false;
}
}
if (s==true) return;
else{
if(i>=size) return ;
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);
}
void build(int x[],int size){
int heapsize=size;
for (int i=(size/2);i>1;i--)
max_heap(x,i,size);
}
int main(){
x[1]=4;
x[2]=1;
x[3]=3;
x[4]=2;
x[5]=16;
x[6]=9;
x[7]=10;
x[8]=14;
x[9]=8;
x[10]=7;
build(x,10);
for (int i=1;i<=10;i++)
cout<<x[i]<<" ";
return 0;
}
此代码失败,而只有max_heap过程工作找到,请告诉我什么是错误的代码?我花了几个小时,但没有发现错误
this code fails,while only max_heap procedure works find,please tell me what is wrong in code?i have spent hours but did not find something wrong yet
推荐答案
我注意到的一件事是,为根元素调用 max_heap
:
One thing I noticed immediatly is that you don't call max_heap
for the root element:
for (int i=(size/2);i>1;i--)
max_heap(x,i,size);
应为
i>=1
这篇关于构建堆过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文