概述:
排序类,可以对任意类型的对象进行排序,包括基本数据类型;
对象类,不仅定义本身数据,同时包含了排序的细节.
排序类(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.38 10 Elmer Fudd ¥10.00 11 RoadRunner ¥5.00 12 Daffy Duck ¥2.50 13 Foghorn Leghorn ¥2.30 14 Bugs Bunny ¥2.00
时间: 2024-10-06 02:30:19