所以我刚刚完成了合并排序的实现,但是我发现我没有删除我丢弃的递归调用返回的内存,所以我为array1和array2添加了删除语句,然后突然我的合并排序不起作用.....为什么在我的函数结尾附近添加删除语句搞砸了一切?我需要释放内存吗?
代码如下:
/**
* Runs merge sort on this ArrayList<T>. Interface function to the central,
* recursive, merge sort function.
*/
template<class T>
void ArrayList<T>::mergeSort() {
T* temp = mergeSort(array, size);
delete [] array;
array = temp;
}
/**
* Runs merge sort on the passed in array. Recursive.
*
* @param array the array to sort.
* @param arraySize the size of the array that is to be sorted.
* @return the sorted array.
*/
template<class T>
T* ArrayList<T>::mergeSort(T* array, int arraySize) {
T* returnArray = array;
//If the array is more than one element.
if (arraySize > 1) {
int size1 = arraySize / 2;
int size2 = arraySize - size1;
T* array1;
T* array2;
//Recurse.
array1 = mergeSort(array, size1);
array2 = mergeSort(array + size1, size2);
returnArray = new T[arraySize];
//Loop through all elements in returnArray.
int i = 0, j = 0, k = 0;
while (i < arraySize) {
//Place the lesser of two elements in returnArray.
if ((array1[j] <= array2[k] && j < size1)
|| k == size2) {
returnArray[i] = array1[j];
j++;
}
else {
returnArray[i] = array2[k];
k++;
}
i++;
}
/ ---这些是问题中的缺点!! ----- /
delete [] array1;
delete [] array2;
}
return returnArray;
}
答案 0 :(得分:3)
当数组大小等于2时,我发现了一个问题 因为你打电话
array1 = mergeSort(array, size1);
array2 = mergeSort(array + size1, size2);
和size1 = 1,size2 = 1 然后这两个调用都将返回,并且变量
中将包含以下值array1 = array;
array2 = array+1;
和array2不是一个分配的内存地址所以删除它应该失败并出现错误或做一些未定义的事情,所以我建议你在继续之前修复它
答案 1 :(得分:1)
我没有仔细查看,但有一点需要注意:当使用大小为mergeSort
的数组调用<= 1
时,它返回传递的数组而不分配新数组但返回时从递归调用,你将尝试删除它。您可以通过添加以下内容来改进代码:
if (size1 > 1)
delete [] array1;
if (size2 > 1)
delete [] array2;