BubbleSort - 实用委托

  概述:

    排序类,可以对任意类型的对象进行排序,包括基本数据类型;

    对象类,不仅定义本身数据,同时包含了排序的细节.

  排序类(BubbleSorter):

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace BubbleSorter {
class BubbleSorter {
public static void Sort<T>(IList<T> list, Func<T, T, bool> comparison) {
bool swapped; //标识是否进行交互操作.
for (int i = ; i < list.Count - ; i++) {
swapped = false;
for (int j = ; j < list.Count - - i; j++) {
if (comparison(list[j], list[j + ])) {
Swap<T>(list, j, j + );
swapped = true;
}
}
if (!swapped) //不进行交互,标识已排好序.
break;
}
} private static void Swap<T>(IList<T> list, int i, int j) {
T tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}
}
}

  对象类:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace BubbleSorter {
class Employee {
public string Name { get; private set; }
public decimal Salary { get; private set; } public Employee(string name, decimal salary) {
Name = name;
Salary = salary;
} public override string ToString() {
return string.Format("{0} {1:C}",Name, Salary); //默认保留两位小数.
} public static bool CompareSalary(Employee e1, Employee e2) {
return e1.Salary < e2.Salary; //按照Salary的降序排序.
}
}
}

  调用类:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace BubbleSorter {
class Program {
static void Main(string[] args) {
Employee[] emplyees = new Employee[]{
new Employee("Bugs Bunny", ),
new Employee("Elmer Fudd", ),
new Employee("Daffy Duck", 2.5m),
new Employee("Wile Coyote", 100.38m),
new Employee("Foghorn Leghorn", 2.3m),
new Employee("RoadRunner", )
};
Console.WriteLine("before sort:");
foreach (Employee e in emplyees) {
Console.WriteLine(e);
} BubbleSorter.Sort<Employee>(emplyees, Employee.CompareSalary); Console.WriteLine("after sort:");
foreach (Employee e in emplyees) {
Console.WriteLine(e);
}
}
}
}

  output:

 before sort:
Bugs Bunny ¥2.00
Elmer Fudd ¥10.00
Daffy Duck ¥2.50
Wile Coyote ¥100.38
Foghorn Leghorn ¥2.30
RoadRunner ¥5.00
after sort:
Wile Coyote ¥100.38
Elmer Fudd ¥10.00
RoadRunner ¥5.00
Daffy Duck ¥2.50
Foghorn Leghorn ¥2.30
Bugs Bunny ¥2.00
上一篇:[JCIP笔记] (二)当我们谈线程安全时,我们在谈论什么


下一篇:【Machine Learning in Action --1】机器学习入门指南