C#之冒泡排序(委托)

来源:互联网 发布:手机芯片性能测试软件 编辑:程序博客网 时间:2024/06/07 08:45
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DelegateDemo1{    class Program    {        static void Main(string[] args)        {            Employee[] employees = {                new Employee("roles_gris0",4000),                new Employee("roles_gris1",1000),                new Employee("roles_gris2",7000),                new Employee("roles_gris3",2000),                new Employee("roles_gris4",9000),                new Employee("roles_gris5",8000),                new Employee("roles_gris6",8000),                new Employee("roles_gris7",6000),                                   };            BubbleSorter.Sort(employees, Employee.CompareSalary);            foreach (var employee in employees)            {                Console.WriteLine(employee);            }            Console.ReadKey();        }    }    /// <summary>    /// 冒泡排序    /// </summary>    class BubbleSorter    {        /// <summary>        /// 冒泡排序 Func<T, T,bool>:封装一个具有两个参数并返回 TResult 参数指定的类型值的方法。        /// </summary>        /// <typeparam name="T">需要比较的是什么类型的数据</typeparam>        /// <param name="sortArry">传递进来的列表 一个数组</param>        /// <param name="comparison">传递进来的委托实例  就是方法名</param>        static public void Sort<T>(IList<T> sortArry, Func<T, T,bool> comparison)        {            int j = 0;            do            {                for (int i = j; i < sortArry.Count - 1; i++)                {                    if(comparison(sortArry[i+1],sortArry[i])){                        T tmp = sortArry[i];                        sortArry[i] = sortArry[i + 1];                        sortArry[i + 1] = tmp;                    }                }                j++;            } while (j < sortArry.Count - 1);        }    }    class Employee    {        public string Name { get; set; }        public double Salary { get; set; }        public Employee(string name, double salary)        {            this.Name = name;            this.Salary = salary;        }        /// <summary>        /// 重写字符串        /// </summary>        /// <returns></returns>        public override string ToString()        {            return string.Format("{0},{1:C}", Name, Salary);        }        /// <summary>        /// 工资比较函数        /// </summary>        /// <param name="e1"></param>        /// <param name="e2"></param>        /// <returns></returns>        public static bool CompareSalary(Employee e1, Employee e2)        {            return e1.Salary < e2.Salary;        }    }}

4 0
原创粉丝点击