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

1. 创建排序对象Employee

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;
        }
    }

 

2. 排序的操作类:BubbleSorter

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);
        }
    }

 

3. 在main方法中操作排序

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();
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。