委托结合泛型实现的冒泡排序算法
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Employee[] employees =
6 {
7 new Employee("Bugs Bunny", 20000),
8 new Employee("Elmer Fudd", 10000),
9 new Employee("Daffy Duck", 25000),
10 new Employee("Wile Coyote", 1000000.38m),
11 new Employee("Foghorn Leghorn", 23000),
12 new Employee("RoadRunner", 50000)
13 };
14 BubbleSorter.Sort(employees, Employee.CompareSalary);
15 foreach (var employee in employees)
16 {
17 Console.WriteLine(employee);
18 }
19 Console.ReadLine();
20 }
21 }
22
23 class BubbleSorter
24 {
25 static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
26 {
27 bool swapped = true;
28 do
29 {
30 swapped = false;
31 for (int i = 0; i < sortArray.Count - 1; i++)
32 {
33 if (comparison(sortArray[i + 1], sortArray[i]))
34 {
35 T temp = sortArray[i];
36 sortArray[i] = sortArray[i + 1];
37 sortArray[i + 1] = temp;
38 swapped = true;
39 }
40 }
41 } while (swapped);
42 }
43 }
44
45 class Employee
46 {
47 public Employee(string name, decimal salary)
48 {
49 this.Name = name;
50 this.Salary = salary;
51 }
52 public string Name { get; private set; }
53 public decimal Salary { get; private set; }
54 public override string ToString()
55 {
56 return string.Format("{0}, {1:C}", Name, Salary);
57 }
58 public static bool CompareSalary(Employee e1, Employee e2)
59 {
60 return e1.Salary < e2.Salary;
61 }
62 }
2 {
3 static void Main(string[] args)
4 {
5 Employee[] employees =
6 {
7 new Employee("Bugs Bunny", 20000),
8 new Employee("Elmer Fudd", 10000),
9 new Employee("Daffy Duck", 25000),
10 new Employee("Wile Coyote", 1000000.38m),
11 new Employee("Foghorn Leghorn", 23000),
12 new Employee("RoadRunner", 50000)
13 };
14 BubbleSorter.Sort(employees, Employee.CompareSalary);
15 foreach (var employee in employees)
16 {
17 Console.WriteLine(employee);
18 }
19 Console.ReadLine();
20 }
21 }
22
23 class BubbleSorter
24 {
25 static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
26 {
27 bool swapped = true;
28 do
29 {
30 swapped = false;
31 for (int i = 0; i < sortArray.Count - 1; i++)
32 {
33 if (comparison(sortArray[i + 1], sortArray[i]))
34 {
35 T temp = sortArray[i];
36 sortArray[i] = sortArray[i + 1];
37 sortArray[i + 1] = temp;
38 swapped = true;
39 }
40 }
41 } while (swapped);
42 }
43 }
44
45 class Employee
46 {
47 public Employee(string name, decimal salary)
48 {
49 this.Name = name;
50 this.Salary = salary;
51 }
52 public string Name { get; private set; }
53 public decimal Salary { get; private set; }
54 public override string ToString()
55 {
56 return string.Format("{0}, {1:C}", Name, Salary);
57 }
58 public static bool CompareSalary(Employee e1, Employee e2)
59 {
60 return e1.Salary < e2.Salary;
61 }
62 }