/*1、首先创建一个冒泡排序类用于实现冒泡排序方法*/
/// <summary> /// 冒泡排序类 /// </summary> public class BubbleSorter { /// <summary> /// 定义静态排序泛型类 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sortArray"></param> /// <param name="compare">带2个参数,返回bool型的排序方法</param> public static void Sort<T>(IList<T> sortArray , Func<T,T,bool>compare){ for ( int i = 0; i < sortArray.Count-1 ; i++ ) { if ( compare ( sortArray[i], sortArray[i + 1] ) ) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; } } } }
/*2、再创建一个员工类,定义员工姓名和薪水属性,构造函数,重写ToString()以及供Func<T>使用的方法*/
/// <summary> /// 员工类 /// </summary> public class Employee { public Employee ( string name, decimal salary ) { this.Name = name; this.Salary = salary; } public string Name { get; set; } public decimal Salary { get; set; } /// <summary> /// 重写ToString()便于显示员工信息 /// </summary> /// <returns></returns> public override string ToString ( ) { return string.Format("Name: {0} Salary:{1}",Name ,Salary ); } /// <summary> /// 排序方法(必须有,且为带2个参数,返回类型为bool型),供委托使用 /// </summary> /// <param name="emp1"></param> /// <param name="emp2"></param> /// <returns></returns> public static bool CompareSalary (Employee emp1,Employee emp2 ) { return emp1.Salary < emp2.Salary; } }
/*3、测试*/
class Program { /// <summary> /// 客户端测试 /// </summary> /// <param name="args"></param> static void Main ( string[ ] args ) { Employee[ ] employees = { new Employee("A",2000), new Employee("B",4000), new Employee("C",3000), new Employee("D",2000), new Employee("E",1000) }; BubbleSorter.Sort ( employees, Employee.CompareSalary ); foreach ( var item in employees ) { Console.WriteLine ( item.ToString ( ) ); } Console.ReadKey ( ); } }