所以我刚刚完成了合并排序的实现,但我突然想到我没有删除从我丢弃的递归调用返回的内存,所以我为 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;
}