I am trying to write an iterative MergeSort function. I have already written it recursively. I have to use this "Merge" function for both the recursive and iterative MergeSort function
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
|
void Merge(vector<int> &a, int front, int mid, int end)
{
int *temp;
int size = end - front + 1;
temp = new int[size];
int front1 = front;
int end1 = mid;
int front2 = mid + 1;
int end2 = end;
int index = 0;
while ((front1 <= end1) && (front2 <= end2))
{
if (a[front1] < a[front2])
{
temp[index] = a[front1];
front1++;
}
else
{
temp[index] = a[front2];
front2++;
}
index++;
}
while (front1 <= end1)
{
temp[index] = a[front1];
front1++;
index++;
}
while (front2 <= end2)
{
temp[index] = a[front2];
front2++;
index++;
}
for (index = 0; index < size; index++)
{
a[front] = temp[index];
front++;
}
delete[] temp;
}
|
Right now, my recursive MergeSort works. But I am unable to get the Iterative MergeSort to work. With this code, I am only able to partially sort the array.
1 2 3 4 5 6 7 8 9 10
|
void IterativeMergeSort(vector<int> &a, int front, int end)
{
for(int i = 1; i <= end; i *= 2)
{
for(int j = i; j <= end; j += (2 * i))
{
Merge(a, j - i, j, min((j + i), end));
}
}
}
|
When I try to sort an array with the following values
[1, 7, 4, 0, 9, 8, 2, 5, 6, 3]
My iterative sort method only sorts part of it
[0, 1, 2, 3, 4, 7, 8, 5, 9, 6]
I tried playing around with the <= and <, and I usually end up getting a vector subscript out of range error. I don't really understand where my code is wrong. Can anyone offer any advice on what I am doing incorrectly?