using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foo(new string[] { });
foo(new int[] { });
}
static void foo(object arr)
{
Console.WriteLine(arr.GetType());
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foo(new string[] { });
foo(new int[] { });
}
static void foo(object arr)
{
Console.WriteLine(arr.GetType());
}
}
}
private static void SelectSort<T>(T[] arr) where T : IComparable<T>
{
SelectSort(arr, 0, arr.Length - 1);
} private static void SelectSort<T>(T[] arr, int start, int end) where T : IComparable<T>
{
while (start <= end)
{
var min = start;
for (var i = start + 1; i <= end; i++)
if (arr[i].CompareTo(arr[min]) < 0)
min = i;
if (min != start)
Swap(arr, start, min);
start++;
}
}
这样,各种各样的实现了 IComparable<T> 接口的对象(整数和字符串都实现了它)就可以调用它。如果你想自定义自己的比大小规则,你仅仅需要将比较大小方法作为方法参数传入,或者将对象封装到自定义的类型中(并且实现比大小接口),仍然可以调用这个排序程序。这里要强调的不是你能抄写什么代码,而是你能理解什么c#程序设计知识!
{
var m = arr[start];
arr[start] = arr[end];
arr[end] = m;
}
例如我们可以写一个测试 var arr1 = new int[] { 2, 38, 27, 223, 28 };
var arr2 = new string[] { "adsfjass", "2384skdfs", "_(&&we2" };
SelectSort(arr1);
SelectSort(arr2);
运行上面4行代码之后,你就发现两个数组都被 SelectSort 方法排好顺序了。学点泛型知识吧。
orif (arr.GetType() == typeof(System.Int32[]))
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foo(new string[] { });
foo(new int[] { });
}
static void foo(object arr)
{
Console.WriteLine(arr.GetType());
}
}
}
{
if(T is string)
Sort(array, true);
else
Sort(array, false);
}
你这个方法不行。人家楼主要的是整形正排序, 字符串反排序。而你写的这个方法,是如何根据类型自己的IComparable排序,和楼主要求不符啊。