冒泡一: 将一个字符串数组按照冒泡排序的方式进行排序
public static int[] GetBubbbleSort( int[] ArrayList) 2 { 3 for (int i = 0; i < ArrayList.Length-1; i++) 4 { 5 for (int j = 0; j < ArrayList.Length-i-1; j++) 6 { 7 int temp; 8 //大于为从小到大,小于为从大到小 9 if (ArrayList[j]>ArrayList[j+1]) 10 { 11 temp = ArrayList[j]; 12 ArrayList[j] = ArrayList[j + 1]; 13 ArrayList[j+1] = temp; 14 } 15 } 16 } 17 return ArrayList; 18 }
冒泡 排序二:
public static int[] BubbleSotr(int[] ArrayList) { bool bubble = true; do { bubble = false; for (int i = 0; i < ArrayList.Length-1; i++) { if (ArrayList[i]>ArrayList[i+1]) { ArrayList[i] = ArrayList[i] + ArrayList[i + 1]; ArrayList[i + 1] = ArrayList[i] - ArrayList[i + 1]; ArrayList[i]=ArrayList[i]-ArrayList[i+1];
bubble = true; } } } while (bubble==true); return ArrayList; } //Bubble冒泡排序的第一种方式
冒泡排序三:
public static void Sort<T>(IList<T> arrayList, Func<T, T, bool> compareration) { bool bubble = true; do { bubble = false; for (int i = 0; i < arrayList.Count - 1; i++) { //传递一个与compareration一样的方法 if (compareration(arrayList[i], arrayList[i + 1])) { T atemp; atemp = arrayList[i]; arrayList[i] = arrayList[i+1]; arrayList[i+1] = atemp; bubble = true; } } } while (bubble == true); }
Emploee类
public class Emploee { public String Name { get; set; } public int Salary { get; set; } public Emploee(string name,int salary) { this.Name = name; this.Salary = salary; } public override string ToString() { return string.Format("Name:{0},Salary:{1}",Name,Salary); } public static bool MyCompareFuction(Emploee e1,Emploee e2) { return e1.Salary>e2.Salary; } }
主函数:实现排序;
class Program { static void Main(string[] args) { Emploee[] emploee = { new Emploee("张三",5000), new Emploee("李四",3000), new Emploee("王五",4500), new Emploee("赵六",3333) }; Bubble.Sort<Emploee>(emploee,Emploee.MyCompareFuction); foreach (var item in emploee) { Console.WriteLine(item); } Console.ReadKey(); } }