我写它来计算数字的反转并且我运行它很好gcc version 4.2.1 20070831 patched
但是当我在代码块上运行它时使用mingw32
它意外关闭。
我调试并发现它在int *left = new int[middle];int *right = new int[length - middle];
但是it just come to error when it recursive on second time
,我不知道它为什么会导致错误并且不知道如何修复它。
我的问题是
1.如何修复错误?
2.是否还有其他堆丢失我没有删除,因为我不确定只是想检查它。
提前谢谢。
#include<iostream>
using namespace std;
int invCount(int*, int);
int merge(int*, int*, int, int*, int);
int main(void){
int array[] = {0, 1, 4, 3, 2};
cout << invCount(array, 5) << "times" << endl;
return 0;
}
int invCount(int *array, int length){
cout << "length:" << length << endl;
if(length <= 1){
return 0;
}
int middle = (length + 1) / 2;
cout << length << endl << middle << endl << length - middle << endl;
cout << endl;
int *left = new int[middle];
int *right = new int[length - middle];
for(int i = 0; i < middle; i ++)left[i] = array[i];//error
for(int i = middle; i < length; i ++)right[i] = array[i];//error
return invCount(left, middle) + invCount(right, length - middle
) + merge(array, left, middle, right, length - middle);
}
int merge(int* array, int* left, int leftLength, int* right, int rightLength){
int i = 0, j = 0, count = 0;
while(i < leftLength || j < rightLength){
if(i == leftLength){
array[i + j] = right[j];
j ++;
}
else if(j == rightLength){
array[i + j] = left[i];
i ++;
}
else if (left[i] <= right[j]){
array[i + j] = left[i];
i ++;
}
else {
array[i + j] = right[j];
j ++;
count += leftLength - i;
}
}
delete[] left;
delete[] right;
return count;
}