首页 > 代码库 > BubbleSort - 实用委托
BubbleSort - 实用委托
概述:
排序类,可以对任意类型的对象进行排序,包括基本数据类型;
对象类,不仅定义本身数据,同时包含了排序的细节.
排序类(BubbleSorter):
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace BubbleSorter { 7 class BubbleSorter { 8 public static void Sort<T>(IList<T> list, Func<T, T, bool> comparison) { 9 bool swapped; //标识是否进行交互操作.10 for (int i = 0; i < list.Count - 1; i++) {11 swapped = false;12 for (int j = 0; j < list.Count - 1 - i; j++) {13 if (comparison(list[j], list[j + 1])) {14 Swap<T>(list, j, j + 1);15 swapped = true;16 }17 }18 if (!swapped) //不进行交互,标识已排好序.19 break;20 }21 }22 23 private static void Swap<T>(IList<T> list, int i, int j) {24 T tmp = list[i];25 list[i] = list[j];26 list[j] = tmp;27 }28 }29 }
对象类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace BubbleSorter { 7 class Employee { 8 public string Name { get; private set; } 9 public decimal Salary { get; private set; }10 11 public Employee(string name, decimal salary) {12 Name = name;13 Salary = salary;14 }15 16 public override string ToString() {17 return string.Format("{0} {1:C}",Name, Salary); //默认保留两位小数.18 }19 20 public static bool CompareSalary(Employee e1, Employee e2) {21 return e1.Salary < e2.Salary; //按照Salary的降序排序.22 }23 }24 }
调用类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace BubbleSorter { 7 class Program { 8 static void Main(string[] args) { 9 Employee[] emplyees = new Employee[]{10 new Employee("Bugs Bunny", 2),11 new Employee("Elmer Fudd", 10),12 new Employee("Daffy Duck", 2.5m),13 new Employee("Wile Coyote", 100.38m),14 new Employee("Foghorn Leghorn", 2.3m),15 new Employee("RoadRunner", 5)16 };17 Console.WriteLine("before sort:");18 foreach (Employee e in emplyees) {19 Console.WriteLine(e);20 }21 22 BubbleSorter.Sort<Employee>(emplyees, Employee.CompareSalary);23 24 Console.WriteLine("after sort:");25 foreach (Employee e in emplyees) {26 Console.WriteLine(e);27 }28 }29 }30 }
output:
1 before sort: 2 Bugs Bunny ¥2.00 3 Elmer Fudd ¥10.00 4 Daffy Duck ¥2.50 5 Wile Coyote ¥100.38 6 Foghorn Leghorn ¥2.30 7 RoadRunner ¥5.00 8 after sort: 9 Wile Coyote ¥100.3810 Elmer Fudd ¥10.0011 RoadRunner ¥5.0012 Daffy Duck ¥2.5013 Foghorn Leghorn ¥2.3014 Bugs Bunny ¥2.00
BubbleSort - 实用委托
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。