在Hepsort程序中获取Sigabrt错误



我在给定的hepsort程序下得到的sigabrt错误如下所示。我是编程的新手,所以我为愚蠢的错误表示歉意。

错误:流产(3)(sigabrt)

中止信号

代码的主要部分如下

  • hepify-一个从给定数组中堆积堆的程序

  • heapsort-根据堆对数组对数组进行排序并将结果保存在数组中的函数

  • main-驱动程序函数


#include <iostream>
#include <math.h>
using namespace std;
void swapper (int first, int second) {
    int temp;
    temp = second;
    second = first;
    first = temp;
}
void heapify (int a[], int size) {
    for(int i = 0; i < (size/2) ; i++) {
        int left = 2*i;
        int right = 2*i + 1;
        if (a[i] < a[left]) {
            swap(a[i], a[left]);
        }
        else if (a[i] < a[right]) { 
            swap(a[i],a[right]);
        }
    }
}
void heapsort(int a[], int size){
    int treesize = size;
    int i = size;
    heapify(a,size);
    while (treesize > 0) {
        cout << " t " << a[i];
        swap(a[i],a[0]);
        i --;
        treesize--;
        heapify(a, treesize);
    }
    cout <<"n";
    for(int i = 0; i < size; i++) {
        cout <<"t"<<a[i];
    }
}
int main() {
    // your code goes here
    int a[] = {10,1,2,11,4,57,12,13,44,14,6,7,9,8,15,16,17,98};
    int arrsize= sizeof(a)/(sizeof(a[0]));
    int pos;
    int ele = 7;
    heapsort(a,arrsize);
    for (int i = 0; i < arrsize; i++){
        cout <<"n "<<a[i];
        cout<<"n"<<arrsize;
    }
    return 0;
}

我不确定程序的其余部分的正确性,但是您之所以获得例外的原因是,因为您正在从界限中访问内存。您以这样的数组大小调用heapsort

heapsort(a, arrsize);

然后将treesizei设置为那个大小:

int treesize = size;
int i = size;

,然后在这些行中:

cout << " t " << a[i];
swap(a[i], a[0]);

i仍然等于arraysize。但最多可以是arraysize-1。当您打印a[i]时,这会导致不确定的行为,并且在以下行中更糟的,不确定的行为会修改数组之外的值。在我的机器上,前者打印垃圾价值,后者会导致堆栈腐败。相反,您应该设置这样的值:

int treesize = size-1;
int i = size-1;

这修复了打印和例外。

最新更新