归并算法的C# [英] MergeSort algorithm in c#
问题描述
我写了下面$ C $下合并类:
I wrote below code for Merge Class :
class Merge
{
public static void sort(IComparable[] a)
{
sort(a, 0, a.Length);
}
public static void sort(IComparable[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N / 2;
sort(a, low, mid);
sort(a, mid, high);
IComparable[] aux = new IComparable[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid) aux[k] = a[j++];
else if (j == high) aux[k] = a[i++];
else if (a[j].CompareTo(a[i]) < 0) aux[k] = a[j++];
else aux[k] = a[i++];
}
for (int k = 0; k < N; k++)
{
a[low + k] = aux[k];
}
}
private static Boolean isSorted(IComparable[] a)
{
for (int i = 1; i < a.Length; i++)
if (a[i].CompareTo(a[i - 1]) < 0) return false;
return true;
}
}
和低于code是实现。我认为以下code should't是错误的!但它的简化版,编译...
And below code is Implementation. i thought below code should't be wrong! but it's does't compile...
class Program
{
static void Main(string[] args)
{
Merge ms = new Merge();
Double[] MyArray = { 80,10,52,7,36,7,67,1,8,54 };
Console.WriteLine("first array is: \n");
for (int k = 0; k < MyArray.Length; k++)
{
Console.Write(MyArray[k]);
if (k<9)
Console.Write(" , ");
}
ms.sort(MyArray); // Error is here. Does't compile !!!
Console.WriteLine("\n");
Console.WriteLine("\nsorted array is: \n ");
for (int k = 0; k < MyArray.Length; k++)
{
Console.Write(MyArray[k]);
if (k<9)
Console.Write(" , ");
}
Console.ReadLine();
}
}
这是简化版,编译。错误是在 ms.sort(MYARRAY);
。
我究竟做错了什么?
请带我......
It's does't compile. Error is in ms.sort(MyArray);
.
What am i doing wrong?
Please lead me...
问候
推荐答案
有两个问题code:
- 签名不符,
IComparable的[]
与不直接兼容双[]
在这种情况下, - 您不能调用
排序
直接通过实例方法
- The signature doesn't match,
IComparable[]
is not directly compatible withdouble[]
in this case - You cannot call the
sort
method through the instance directly
变化的最小量来解决,这将是使通用的方法,并调用 Merge.sort
而不是 ms.sort
。
The minimal amount of changes to fix this would be to make the method generic, and call Merge.sort
instead of ms.sort
.
下面是我会怎么实施排序
:
public static void sort<T>(T[] a)
where T : IComparable<T>
{
sort(a, 0, a.Length);
}
public static void sort<T>(T[] a, int low, int high)
where T : IComparable<T>
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N / 2;
sort(a, low, mid);
sort(a, mid, high);
T[] aux = new T[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid) aux[k] = a[j++];
else if (j == high) aux[k] = a[i++];
else if (a[j].CompareTo(a[i]) < 0) aux[k] = a[j++];
else aux[k] = a[i++];
}
for (int k = 0; k < N; k++)
{
a[low + k] = aux[k];
}
}
请注意,我改变使用 T
而不是 IComparable的
,并增加了一个约束说我们需要一个 T
实现 IComparable的&LT; T&GT;
Note that I changed to using T
instead of IComparable
, and added a constraint saying we need a T
that implements IComparable<T>
.
此外,从这种变化中您的来电:
Additionally, change your call from this:
ms.sort(...);
这样:
Merge.sort(...);
这篇关于归并算法的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!