所以我用 C++ 编写了一个堆排序程序,它接受一个双精度数组和数组的大小,然后对其进行排序。该程序可以工作,但是当我尝试传递大于 1000 的数组时,我得到“总线错误:10”我认为这与内存的分配方式有关,但是我似乎找不到解决方案。
#ifndef _HEAPSORT_
#define _HEAPSORT_
void Heapsort(double arrayToSort[], int sizeOfArray);
void Heapsort(double arrayToSort[], int sizeOfArray)
{
// Building Heap:
// ==========================
int halfSize = sizeOfArray-1 / 2;
for(int i = halfSize; i >= 0; i--){
double temp = arrayToSort[i];
int I1 = i, I2 = i+i;
do {
if( I2 < sizeOfArray - 1 && arrayToSort[I2+1] > arrayToSort[I2] ) { I2++; }
if( arrayToSort[I2] > temp ){
arrayToSort[I1] = arrayToSort[I2];
I1 = I2;
I2 = I1+I1;
} else {
I2 = sizeOfArray;
}
} while ( I2 < sizeOfArray );
arrayToSort[I1] = temp;
}
// Sorting Heap:
// =========================
for(int i = sizeOfArray-1; i >= 2; i--){ // i is the number of still competing elements
double temp = arrayToSort[i];
arrayToSort[i] = arrayToSort[0]; // store top of the heap
int I1 = 0, I2 = 1;
do {
if((I2+1) < i && arrayToSort[I2+1] > arrayToSort[I2] ) { I2++; }
if(arrayToSort[I2] > temp ){
arrayToSort[I1] = arrayToSort[I2];
I1 = I2;
I2 = I1+I1;
} else {
I2 = i;
}
} while( I2 < i );
arrayToSort[I1] = temp;
}
double Temp = arrayToSort[1];
arrayToSort[1] = arrayToSort[0];
arrayToSort[0] = Temp;
}
#endif /* _HEAPSORT_ */
任何有关如何解决此问题的见解将不胜感激。这是我分配内存的代码。
#include <iostream>
#include "heapsort.h"
#include "rmaset.h"
#include "ranmar.h"
#include "common.h"
using namespace std;
int main(void)
{
const int size = 1000;
struct Common block;
rmaset(block);
double array[size];
for(int i = 0; i < size; i++){
array[i] = ranmar(block);
}
Heapsort(array,size);
return 0;
}
这只是创建一个结构,然后将其传递给初始化它的函数,然后传递给另一个函数ranmar,该函数用随机数填充它。我已经彻底检查了所有其他功能,并确定错误来自 Heapsort 功能。