我写了一个合并排序程序(我写了基本算法)——它工作得很好。但是,由于我必须从一个非常大的文件中读取整数,所以我想在递归调用中动态声明数组。因此我写了以下代码,但是它给了我一些错误,你能帮我确定我在哪里犯了错误吗?
该程序实际上是计算数组中反转的数量(如果 i < j 和 arr[i]>arr[j] ,那么这是一个反转)。我编写的程序如下:我不想每次进行递归调用时都在堆栈上声明一个包含 10000 个整数的数组
我得到的错误是:std::bad_alloc at memory location 0x004dd940 ..我已经编辑了这个问题,所以它包含了错误消息。执行中断,Visual Studio 进入调试模式并打开文件 osfinfo.c
#include<stdio.h>
#include <iostream>
using namespace std;
unsigned int mixAndCount(int * arr,int low, int mid,int high) {
int *num = new int[high-low+1];// THIS IS WHERE THE ERROR OCCURS
int l = low ;
int r = mid+1;
unsigned int count=0;
int i =low;
while((l<=mid)&&(r<=high))
{
if(arr[l]<=arr[r])
{
num[i]=arr[l];
l++;
}
else
{
num[i]=arr[r];
r++;
count=count + (mid-l+1);
}
i++;
}
if(l>mid)
{
for(int k=r;k<=high;k++)
{
num[i]=arr[k];
i++;
}
}
else
{
for(int k=l;k<=mid;k++)
{
num[i]=arr[k];
i++;
}
}
for(int k=low;k<=high;k++) arr[k]=num[k];
delete[] num;
return count;
}
unsigned int mergeAndCount(int * arr, int low , int high ) {
if(low>=high) {
return 0;
}
else {
int mid = (low+high)/2;
unsigned int left = mergeAndCount(arr, low , mid);
unsigned right = mergeAndCount(arr, mid+1, high);
unsigned int split = mixAndCount(arr, low , mid , high);
return left+right+split;
}
}
int main ()
{
int numArr[100000];
FILE * input = fopen("IntegerArray.txt", "r");
int i =0;
while(!feof(input)) {
int num;
fscanf(input, "%d", &num);
numArr[i] = num;
i++;
}
fclose(input);
unsigned int count = mergeAndCount(numArr,0, i-1 );
cout<<count<<endl;
return 0;
}