C# 委托实现冒泡排序
委托实现员工根据工资升序排列
首先定义员工类
1 class Employee 2 { 3 public string Name { get; private set; } 4 public decimal Salary { get; private set; } 5 6 public Employee(string name, decimal salary) 7 { 8 this.Name = name; this.Salary = salary; 9 } 10 11 public override string ToString() 12 { 13 return string.Format("{0},{1:C}",Name,Salary); 14 } 15 public static bool CompareSalary(Employee e1,Employee e2) 16 { 17 return e1.Salary < e2.Salary; 18 } 19 }
重写sort方法
1 class BubbleSorter 2 { 3 public static void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) 4 { 5 bool swapped = true; 6 do 7 { 8 swapped = false; 9 for (int i = 0; i < sortArray.Count - 1; i++) 10 { 11 if (comparison(sortArray[i + 1], sortArray[i])) 12 { 13 T temp = sortArray[i]; 14 sortArray[i] = sortArray[i + 1]; 15 sortArray[i + 1] = temp; 16 swapped = true; 17 } 18 } 19 } while (swapped); 20 21 22 } 23 }
调用 方法实现排序
1 Employee[] employees = 2 { 3 new Employee("Bugs Bunny", 20000), 4 new Employee("Elmer Fudd", 10000), 5 new Employee("Daffy Duck", 25000), 6 new Employee("Wile Coyote", 1000000.38m), 7 new Employee("Foghorn Leghorn", 23000), 8 new Employee("RoadRunner", 50000) 9 }; 10 11 BubbleSorter.Sort(employees, Employee.CompareSalary); 12 13 foreach (var employee in employees) 14 { 15 Console.WriteLine(employee); 16 }
鹰击长空,鱼翔浅底