Reputation: 1266
Hey I'm making a generic implementation of an ArrayList in C++ and part of it is implementing MergeSort, but now that I've started testing it I'm running into an odd problem. In my tests I'm using type int for simplicity, and on the second function signature below I'm getting the error:
initializing argument 1 of 'T* ArrayList<T>::mergeSort(T*, int) [with T = int]' [-fpermissive]
Then on the recursive calls in the second function I get this error:
invalid conversion from 'int' to 'int*' [-fpermissive]
I don't understand why it thinks I'm trying to convert from an int to an int...shouldn't both be of type int* !? I'm kind of a noob to C++, and especially generics in C++ (although I'm well versed in Java) so any helpful pointers (no pun intended) are appreciated!
/**
* Runs merge sort on this ArrayList<T>. Interface function to the central,
* recursive, merge sort function.
*/
template<class T>
void ArrayList<T>::mergeSort() {
mergeSort(array, size);
}
/**
* 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 arraySize isn't 1, recurse. Otherwise return the single element array.
if (arraySize != 1) {
returnArray = new T[arraySize];
//Split arrays further. Recurse.
returnArray = mergeSort(array[0], arraySize / 2);
returnArray += arraySize / 2;
returnArray = mergeSort(array[arraySize / 2], arraySize - (arraySize / 2));
}
return returnArray;
}
Upvotes: 1
Views: 157
Reputation: 3911
In your two recursive calls, you are not passing pointers, you are passing the values in the array at those indices.
if (arraySize != 1) {
returnArray = new T[arraySize];
//Split arrays further. Recurse.
returnArray = mergeSort(array[0], arraySize / 2);
returnArray += arraySize / 2;
returnArray = mergeSort(array[arraySize / 2], arraySize - (arraySize / 2));
}
Change your recursive calls to either:
returnArray = mergeSort(&array[0], arraySize / 2);
returnArray = mergeSort(&array[arraySize / 2], arraySize - (arraySize / 2));
or:
returnArray = mergeSort(array, arraySize / 2);
returnArray = mergeSort(array + (arraySize / 2), arraySize - (arraySize / 2));
I'm not clear on what your first error is, it looks like you've cut off part of the error message.
Upvotes: 3