冒泡排序拓展 其他数据类型的排序
class Employee//定义employee类 { public string Name { get; private set; } public int Salary { get; private set; } public Employee(string name, int salary) { this.Name = name; this.Salary = salary; } public static bool Compare(Employee e1,Employee e2) { if (e1.Salary > e2.Salary) return true; return false; } } static void CommonSort<T>(T[] array,Func<T,T,bool> compareMethod)//T表示数据类型不确定,使用委托。 { bool swapped = true; do { swapped = false; for (int i = 0; i < array.Length - 1; i++) { if (compareMethod(array[i],array[i + 1])) { T temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swapped = true; } } } while (swapped); } static void Main(string[] args) { Employee[] employees = new Employee[] { new Employee("a", 12), new Employee("b", 34), new Employee("c", 5) }; CommonSort<Employee>(employees,Employee.Compare); foreach (Employee em in employees) { Console.WriteLine(em.Salary); } Console.ReadKey(); }