C#是微软公司发布的一种面向对象的、运行于.NET Framework之上的高级程序设计语言。并定于在微软职业开发者论坛(PDC)上登台亮相。C#是微软公司研究员Anders Hejlsberg的最新成果。C#看起来与Java有着惊人的相似;它包括了诸如单一继承、接口、与Java几乎同样的语法和编译成中间代码再运行的过程。
C#冒泡排序具体代码如下:
public static void BubbleSort(IComparable[] array) { int i, j; IComparable temp; for (i = array.Length - 1; i > 0; i--) { for (j = 0; j < i; j++) { if (array[j].CompareTo(array[j + 1]) > 0) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } }
泛型封装,具体代码如下:
public static void BubbleSort<T>(T[] array) where T : IComparable { int length = array.Length; for (int i = 0; i < length; i++) { T temp = array[i]; for (int j = i; j < length; j++) { if (temp.CompareTo(array[j]) >0) { temp = array[j]; array[j] = array[i]; array[i] = temp; } } } }
测试代码如下:
int[] array = new int[] {20,19,45,40,90,66,18,65,12,145,122,80,97,47}; Console.WriteLine("before bubble sort"); foreach (int i in array) { Console.Write(i+"->"); } Console.WriteLine(); SortHelper.BubbleSort<int>(array); Console.WriteLine("after bubble sort"); foreach (int i in array) { Console.Write(i + "->"); } Console.WriteLine(); Console.Read();
运行结果如下:
before bubble sort 20->19->45->40->90->66->18->65->12->145->122->80->97->47-> after bubble sort 12->18->19->20->40->45->47->65->66->87->90->97->122->145->