.net 使用委托实现冒泡排序

1. 创建排序对象Employee

.net 使用委托实现冒泡排序
class Employee
    {
        public Employee(string name, decimal salary)
        {
            this.Name = name;
            this.Salary = salary;
        }

        public string Name { get; set; }
        public decimal Salary { get; set; }

        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;
        }
    }
.net 使用委托实现冒泡排序

 

2. 排序的操作类:BubbleSorter

.net 使用委托实现冒泡排序
class BubbleSorter
    {
        /// <summary>
        /// 1.传入需要被排序的集合,和一个比较大小的方法引用
        /// 2.遍历集合,比较前后2个参数的大小,传回一个bool类型
        /// 3.如果为true,则交换前后2个参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sortArray"></param>
        /// <param name="comparison"></param>
        static public void Sort<T>
            (IList<T> sortArray, Func<T, T, bool> comparison)
        {
            bool swapped = true;
            do
            {
                swapped = false;
                for (int i = 0; i < sortArray.Count - 1; i++)
                {
                    if (comparison(sortArray[i + 1], sortArray[i]))
                    {
                        T temp = sortArray[i];
                        sortArray[i] = sortArray[i + 1];
                        sortArray[i + 1] = temp;
                        swapped = true;
                    }
                }
            } while (swapped);
        }
    }
.net 使用委托实现冒泡排序

 

3. 在main方法中操作排序

.net 使用委托实现冒泡排序
static void Main(string[] args)
        {
            
            Employee[] employees =
            {
                new Employee("AAAA",20000),
                new Employee("BBBB",10000),
                new Employee("CCCC",25000),
                new Employee("DDDD",20000.38m),
                new Employee("GGGG",23000),
                new Employee("EEEE",50000),
                new Employee("FFFF",22000),
            };

            BubbleSorter.Sort(employees, Employee.CompareSalary);

            foreach (var employee in employees)
            {
                Console.WriteLine(employee);
            }

            Console.ReadKey();
}
.net 使用委托实现冒泡排序

.net 使用委托实现冒泡排序

上一篇:实现简单的php导出excel


下一篇:网页布局笔记2—基于浮动的布局