Hey, everyone.
I'm working on an assignment for programming, and I cannot for the life of me make my merge sort work. I know I am definitely doing something wrong, but I do not know what it is that I am doing wrong.
I've done this before, but with different methods with different arguments.
I am not allowed to change the method arguments.
If you could provide some feedback for me as to what I am doing wrong here, I would greatly appreciate it.
I'm not looking for a whole solution - I know what I need to do for merge sort, but there is something inherently wrong with my code, and I have no idea where I am going wrong.
I know merge sort only needs one scratch array, but the method arguments are making it difficult for me to see how to use that one scratch array.
Below is the code from my most recent attempt.
I know it is not sorting because I am using an assert to make sure it is sorted.
My other sort methods are working (bogo sort, quick sort, insertion sort, and selection sort), I just can't get merge sort to work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
template<typename T>
void Sorts<T>::mergeSort(T arr[], int size)
{
if (size < 2)
return;
int middle = size / 2;
T* left = new T[middle];
T* right = new T[size - middle];
for (int i = 0; i < middle; i++)
{
left[i] = arr[i];
}
for (int i = middle; i < size; i++)
{
right[i - middle] = arr[i];
}
mergeSort(left, middle);
mergeSort(right, size - middle);
merge(left, right, middle, size - middle);
T* temp = new T[size];
for (int i = 0; i < middle; i++)
{
temp[i] = left[i];
}
for (int i = middle; i < size; i++)
{
temp[i] = right[i - middle];
}
for (int i = 0; i < size; i++)
{
arr[i] = temp[i];
}
delete [] left;
delete [] right;
delete [] temp;
}
/** WHY CAN'T WE INCLUDE T arr[] IN THE MERGE FUNCTION?!*/
/** THAT WOULD MAKE THIS IMPLEMENTATION SO MUCH MORE SIMPLE */
template<typename T>
void Sorts<T>::merge(T* a1, T* a2, int size1, int size2)
{
T* arr = new T[size1 + size2];
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2)
{
if (a1[i] <= a2[j])
{
arr[k] = a1[i];
i++;
k++;
}
else
{
arr[k] = a2[j];
k++;
j++;
}
}
while (i < size1)
{
arr[k] = a1[i];
i++;
k++;
}
while (j < size2)
{
arr[k] = a2[j];
k++;
j++;
}
for (int i = 0; i < size1; i++)
{
a1[i] = arr[i];
}
for (int i = size1; i < size1 + size2; i++)
{
a2[i - size1] = arr[i + size1];
}
delete [] arr;
}
|
EDIT: Nevermind. Banged my head on my keyboard and figured it out. Poor keyboard.