Array.Sort的执行步骤
主要问题是
1、既然Array.Sort本身具体有排序作用为什么还要参数 myComparer?难道仅仅是为了倒序?
2、myReverserClass::Compare(object x, object y)中的X,Y哪里来的?程序中并没有显式的调用compare函数
// 程序如下
using System;
using System.Collections;
public class SamplesArray
{
public class myReverserClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y )
{
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main()
{
// Creates and initializes a new Array and a new custom comparer.
String[] myArr = { "The", "QUICK", "BROWN", "FOX", "jumps", "over", "the", "lazy", "dog" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintIndexAndValues( myArr );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myArr, 1, 3, myComparer ); //【×××】
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintIndexAndValues( myArr );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myArr, myComparer ); //【×××】
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintIndexAndValues( myArr );
}
public static void PrintIndexAndValues( String[] myArr )
{
for ( int i = 0; i < myArr.Length; i++ )
{
Console.WriteLine( " [{0}] : {1}", i, myArr[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
------解决方案--------------------Sort只是系统封装的简单排序
通过继承IComparer接口 你可以灵活的进行排序 包括一些需要中间处理的逻辑
------解决方案--------------------2、myReverserClass::Compare(object x, object y)中的X,Y哪里来的?程序中并没有显式的调用compare函数
x, y 是指序列中的任意两个元素。就是写在什么情况下 x > y , x = y, or x < y
------解决方案--------------------如果没有IComparable,如果你没有实现自己的两个对象的比较,ArrayList是不知道两个对象应该怎么比较的。因为它知道的只是一个未知的对象链表。