Reputation: 25
For a school assignment, I have to implement mergesort.
I've used this code to do the trick:
static int[] MergeSort(int[] C)
{
int left = 0;
int right = C.Length;
int middle = (left + right) / 2;
int[] A, B;
A = new int[middle];
B = new int[middle];
if (C.Length == 0 || C.Length == 1)
{
return C;
}
else
{
for (int i = left; i < middle; i++)
{
A[i] = C[i];
B[i] = C[middle + i];
}
MergeSort(A);
MergeSort(B);
return Merge(A, B, C);
}
}
static int[] Merge(int[] A, int[] B, int[] C)
{
int i, j, k;
i = j = k = 0;
int n = A.Length;
int m = B.Length;
int c = C.Length;
int middle = C.Length / 2;
while (i < n && j < m)
{
if (A[i] < B[j])
{
C[k] = A[i];
i++;
}
else
{
C[k] = B[j];
j++;
}
k++;
if (i == n)
{
for (int b = i; b < B.Length; b++)
{
C[middle + b] = B[b];
}
}
else
{
for (int a = i; a < A.Length; a++)
{
C[middle + a] = A[a];
}
}
}
return C;
}
It does not work for a lot of different rows though. I've already debugged and checked if there was something wrong with constraints, but I can't seem to find the problem.
Thanks in advance!
Upvotes: 2
Views: 196
Reputation: 8656
In addition to Guffa answer, you should edit the code of the Merge method like this:
while (i < n && j < m)
{
if (A[i] < B[j])
{
C[k] = A[i];
i++;
}
else
{
C[k] = B[j];
j++;
}
k++;
}
if (i == n)
{
for (int b = j; b < B.Length; b++)
{
C[k++] = B[b];
}
}
else
{
for (int a = i; a < A.Length; a++)
{
C[k++] = A[a];
}
}
While loop block should end right after k++ and in first for loop you should initialize b with j instead of i. Also, watch out for the index of the next element of the C array, it is k, not necessarily middle + a or b.
Upvotes: 1
Reputation: 700222
The first thing I spot is how you split the array into two:
A = new int[middle];
B = new int[middle];
If the length is not even, you will be leaving out the last item. You should have:
A = new int[middle];
B = new int[right - middle];
Then you would use separate loops for them, as they can be different in length:
for (int i = left; i < middle; i++) {
A[i - left] = C[i];
}
for (int i = middle; i < right; i++) {
B[i - middle] = C[i];
}
Upvotes: 2