对于学校作业,我必须实施归并排序。
我用这段代码来做到这一点:
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;
}
但它不适用于许多不同的行。我已经调试并检查了约束是否有问题,但我似乎找不到问题。
提前致谢!