So I just finished my implementation of merge sort but it occurred to me that I didn't delete the memory returned from recursive calls that I was discarding, so I added delete statements for array1 and array2, and then suddenly my merge sort doesn't work.....Why does adding the delete statements near the end of my function screw everything up? Do I need to free the memory?
The code is below:
/**
* 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++;
}
/---THESE ARE THE DELETES IN QUESTION!!-----/
delete [] array1;
delete [] array2;
}
return returnArray;
}
i see a problem when array size is equal to 2 since you call
array1 = mergeSort(array, size1);
array2 = mergeSort(array + size1, size2);
and size1=1,size2=1 then both of these calls will return and you will have the following values in the variables
array1 = array;
array2 = array+1;
and array2 isn't an allocated memory address so deleting it should fail with an error or do something undefined so i would suggest fixing that before you continue