【发布时间】:2013-03-27 23:30:13
【问题描述】:
我为合并类编写了以下代码:
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;
}
}
下面的代码是实现。我认为下面的代码应该没有错!但它没有编译...
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); 中。
我究竟做错了什么?
请带我...
问候
【问题讨论】:
-
尝试调用 MyArray.sort();没关系-我认为这是一种扩展方法...如果您适当地更改签名-添加“this”关键字,您可以扩展数组对象。
-
我有两个错误。第一个:
Error 1 The best overloaded method match for 'MergeSort.Merge.sort(System.IComparable[])' has some invalid arguments c:\users\hamed\documents\visual studio 2010\Projects\MergeSort\MergeSort\Program.cs 22 9 MergeSort,第二个是Error 2 Argument 1: cannot convert from 'double[]' to 'System.IComparable[]' c:\users\hamed\documents\visual studio 2010\Projects\MergeSort\MergeSort\Program.cs 22 17 MergeSort
标签: c# algorithm console mergesort