c++ - 建立堆程序

标签 c++ data-structures

<分区>

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 程序可以找到,请告诉我代码中有什么问题?我已经花了几个小时但还没有发现问题

最佳答案

我立即注意到的一件事是您没有为根元素调用 max_heap:

for (int i=(size/2);i>1;i--)
    max_heap(x,i,size);

应该是

i>=1

关于c++ - 建立堆程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7823480/

相关文章:

algorithm - heapify VS 构建堆

java - 将一个变量用作数据类型不同但名称相同的另一个变量

c++ - 在 C++ 中查找等价类数量的有效方法

c++ - 来自高方差区域 OpenCV 的文本边界框

c++ - 与引号连接会导致错误

c++ - C++ 是否提供与 pair<T1, T2> 相当的 "triple"模板?

c++ - 寻找一种良好的空间分区数据结构以从中快速生成数百万个原子键

python - 打印n叉树python的所有路径

带数据结构指针参数的 C 函数

c++ - 我可以使用预处理器将一种类型声明替换为另一种类型声明吗?