【问题标题】:Heapsort using Priority queue C++使用优先级队列 C++ 进行堆排序
【发布时间】:2014-04-29 01:29:09
【问题描述】:

我的代码用于将数据放入数组,但是当我打印出来时,它总是在第一个数字后崩溃。我的bubbledown函数一定有问题,你能指出它有什么问题吗?提前谢谢你。

#include<iostream>
#include <string>
#include<fstream>
using namespace std;

void bubbleup(int pq[], int back);
void bubbledown(int pq[], int front, int back);
void swap(int &a, int &b);

int main(){
    ifstream infile;
    ofstream outfile;
    string input, output;
    int size,number;
    int front=1, back=0;
    int *pq=new int[size]; // dynamically allocate array
    cout<<"What's the input file name?"<<endl;
    getline(cin, input); // get the input name
    infile.open(input.c_str());// open the input file

    while(!(infile.eof())){
      infile>>number; // infile to an integer type variable first instead of an array. this is why your program doesn't work!!!!!
      back++;
      pq[back]=number;
      bubbleup(pq,back);
      for(int i=1;i<=back;i++)
        cout<<pq[i]<<" ";
      cout<<endl;
    }
    cout<<"what's the output file name?"<<endl;
    getline(cin, output);
    outfile.open(output.c_str());
    while(back!=0){
        cout<< pq[front]<<endl;
        outfile<< pq[front]<<endl;
        pq[front]=pq[back];
        back--;
        bubbledown(pq,front,back);
    }
}
//bubbleup function
void bubbleup(int pq[], int back)
{
     int fatherindex=back/2;
        while(!(pq[back]>=pq[fatherindex])||!(back==1)){

          if(pq[back]<pq[fatherindex])
           swap(pq[back],pq[fatherindex]);
           back=fatherindex;
           fatherindex=back/2;
        }   
}

//bubbledown function
void bubbledown(int pq[], int front, int back){
    int fatherindex=front,kidindex;
    while(2*fatherindex+1 <= back){
        kidindex=2*fatherindex+1;
        if((kidindex+1<back) && (pq[kidindex]<pq[kidindex+1])){
           kidindex++;
           }
        if(pq[fatherindex] > pq[kidindex]){
           swap(pq[fatherindex],pq[kidindex]);
           fatherindex=kidindex;
        }
        else
          return;
    }
}
//swap function
void swap(int &a, int &b){
    int t=a;
        a=b;
        b=t;
}

【问题讨论】:

标签: c++ sorting heap priority-queue


【解决方案1】:

需要注意的几个问题

  • 您在使用之前不会初始化size,因此您的 pq 内存可以是任意大小。

  • 您正在对数组使用基于 1 的访问,因此请确保分配的数量超出您的需要。

  • while(!back==0) 可以工作,但它在 int 上执行布尔逻辑,然后将结果与 int 进行比较。 while(back!=0) 更容易阅读,并且会产生更少的编译器警告。

编辑:你的 bubbleDown 函数也有一个无限循环,当两者都没有触发测试时。

【讨论】:

  • 谢谢!我做了一些更改,它现在运行,但没有打印出正确的数据。你能再看一下我的代码吗?
  • @user2836989:Stack Overflow 不是调试服务。你不能只要求别人找出你代码中的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2021-02-06
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多