构建堆过程崩溃期间worlking [英] build heap procedure crash during it's worlking

查看:92
本文介绍了构建堆过程崩溃期间worlking的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的max_heap过程工作发现自己,但当我试图添加build-Max-Heap过程,它不工作,请帮助我

my max_heap procedure works find itself,but when i tried to add build-Max-Heap procedure,it does not work ,please help me

#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;
}

请告诉我为什么当u运行时它停止工作max_heap工作正常

please tell me why it stops working when u run?max_heap works fine itself

推荐答案

我认为当 i == largest 无限递归。当将 max_heap 的调用移动到前面的 if 块时,崩溃消失。

I think that when i==largest you get stuck in an infinite recursion. The crash goes away when the call to max_heap is moved into the preceding if block.

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

此外,您必须更改 build 循环以包含根元素。

In addition, you must change the build loop to include the root element.

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

这篇关于构建堆过程崩溃期间worlking的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆