一、普通冒泡排序
冒泡排序想必大家都不陌生,原理也就不介绍了,直接看代码吧
(1)第一种
1 static void Sort(int[] unsorted) 2 { 3 for (int i = 0; i < unsorted.Length-1; i++) 4 { 5 for (int j = 0; j < unsorted.Length-i-1; j++) 6 { 7 if (unsorted[j] > unsorted[j+1]) 8 { 9 int temp = unsorted[j]; 10 unsorted[j] = unsorted[j+1]; 11 unsorted[j+1] = temp; 12 } 13 } 14 } 15 }
(2)第二种(与第一种并没有本质的区别,只不过加了一个标识位,当检索一遍发现没有交换时便停止循环,可以稍微提高下效率吧)
1 static void Main(string[] args) 2 { 3 int[] array = new int[] { 1,23,23,14,14,24,25,525,66}; 4 Sort(array); 5 foreach (var item in array) 6 { 7 Console.Write(item+" "); 8 } 9 } 10 11 //从小到大排序 12 static void Sort(int[] sortArray) 13 { 14 bool isChange = true; 15 do 16 { 17 isChange = false; 18 for (int i = 0; i < sortArray.Length-1; i++) 19 { 20 if (sortArray[i] > sortArray[i + 1]) 21 { 22 int temp = sortArray[i]; 23 sortArray[i] = sortArray[i + 1]; 24 sortArray[i + 1] = temp; 25 isChange = true; 26 } 27 } 28 29 } while (isChange); 30 } 31
二、通用类型冒泡排序
这里我们对一个Hero类进行排序(根据Hero中的attack属性),Compare方法由Hero类本身实现,方便委托
Hero类如下:
1 public class Hero 2 { 3 string Name { get; set; } 4 int attack { get; set; } 5 float speed { get; set; } 6 Hero(string name,int attack,float speed=10f) 7 { 8 this.Name = name; 9 this.attack = attack; 10 } 11 12 //h1的attack大于h2的attack返回true 否则返回false 13 public static bool Compare(Hero h1, Hero h2) 14 { 15 if (h1.attack > h2.attack) 16 return true; 17 } 18 }
排序方法为Sort<T>(T[] sortArray,Func<T,T,bool> Compare),比较采用Func委托
具体实现如下:
1 static void Sort<T>(T[] sortArray,Func<T,T,bool> Compare) 2 { 3 bool isChange = true; 4 do 5 { 6 isChange = false; 7 for (int i = 0; i < sortArray.Length - 1; i++) 8 { 9 if (Compare(sortArray[i],sortArray[i+1])) 10 { 11 T temp = sortArray[i]; 12 sortArray[i] = sortArray[i + 1]; 13 sortArray[i + 1] = temp; 14 isChange = true; 15 } 16 } 17 18 } while (isChange); 19 }
1 static void Main(string[] args) 2 { 3 Hero[] heroArray = new Hero[] 4 { 5 new Hero("a",12), 6 new Hero("s",2), 7 new Hero("d",144), 8 new Hero("f",15), 9 new Hero("g",6), 10 new Hero("w",0), 11 }; 12 Sort<Hero>(heroArray, Hero.Compare); 13 foreach (var item in heroArray) 14 { 15 Console.WriteLine(item.ToString()); 16 } 17 Console.ReadKey(); 18 }
其中Hero类中重写了ToString()方法方便输出
public override string ToString() { return "name:"+this.Name+" attack:"+this.attack+" speed:"+this.speed; }
输出结果如下:
原文:http://www.cnblogs.com/zhangbaochong/p/4844045.html