首页 > 代码库 > IComparable

IComparable

public class Program    {       static void Main(String[] args)        {            var myInt = new[] { 20, 4, 5, 1, 6 };            Array.Sort(myInt);            foreach (var i in myInt)                Console.WriteLine("{0}", i);            Console.ReadLine();        }    }/*Array类的sort方法其实依靠一个叫做IComparable的接口!public interface IComparable{    int CompareTo(object obj);} sort 使用的算法依赖于元素的CompareTo方法来决定两个元素的次序。int类型实现了IComparable*/class Program    {        static void Main(string[] args)        {int i,j,t;         var myInt = new[] { 20, 4, 5, 1, 6};         for (i = 0; i <myInt.Length-1; i++)          for (j = 0; j < myInt.Length - 1-i; j++)              if (myInt[j].CompareTo(myInt[j + 1]) > 0)//myInt[j].CompareTo(myInt[j+1])<0则为降序排序,正好相反的!            {  t=myInt[j];               myInt[j] = myInt[j+1];               myInt[j + 1] = t;                          }         for (i = 0; i <myInt.Length; i++)             Console.WriteLine("{0}", myInt[i]);         Console.ReadLine();                   }    }

 

IComparable