我正在尝试读取包含随机数列表的文本文件,并使用合并排序对它们进行排序以显示。这些数字被读入动态数组。不幸的是,每当我尝试删除未使用的数组时,都会检测到堆损坏错误。
合并排序功能:
void mergesort(int *arr, int first, int last)
{
if(first < last)
{
int middle = ((first + last)/2);
mergesort(arr, first, middle);
mergesort(arr, middle+1, last);
merge(arr, first, last);
}
}
当我删除 tempArr 时,合并函数中发生错误:
void merge(int *arr, int first, int last)
{
int *tempArr = new int[last];
int mid = (first+last)/2;
int first1 = first;
int last1 = mid;
int first2 = mid + 1;
int last2 = last;
int index = first1;
for(; (first1 <= last1) && (first2 <= last2); ++index)
{
if (arr[first1] < arr[first2])
{
tempArr[index] = arr[first1];
++first1;
}
else
{
tempArr[index] = arr[first2];
++first2;
}
}
for(; first1 <= last1; ++first1, ++index)
tempArr[index] = arr[first1];
for(; first2 <= last2; ++first2, ++index)
tempArr[index] = arr[first2];
for(index=first;index<=last;++index)
arr[index] = tempArr[index];
delete [] tempArr;
}