算法_通用冒号排序

员工类

using System;
namespace int冒泡排序
{
    public class Employee
    {

            private String name;
            private int xinShui;
            //封装属性
            public String Name { get; private set; }
            public int XinShui { get; private set; }

            //构造方法 用来赋值
            public  Employee(String name,int xinShui) {
                this.name = name;
                this.xinShui = xinShui;
            }
            
            //比较两个值 大小
            public static bool CommonSort(Employee e1,Employee e2)
            {
                if (e1.xinShui > e2.xinShui) {
                     return true;
                 }
                 return false;
            }

            //重写tostirng方法 输出值
            public override string ToString() {
                Console.WriteLine(name+"=>"+xinShui);
                return "";
            }
        }

    
}
//通用排序 方法
            //T 任意类型
            void CommonSort<T>(T[] array,Func<T,T,bool> EmployeeMethod)
            {
                //是否循环
                bool aa = true;
                do
                {
                    aa = false;
                    for (int i = 0; i < array.Length - 1; i++)
                    {
                        //比较 两个数的值的大小
                        if (EmployeeMethod(array[i],array[i+1]))
                        {
                            //进行交换
                            T empty = array[i];
                            array[i] = array[i + 1];
                            array[i + 1] = empty;
                            aa = true;
                        }
                    }

                } while (aa);
                //输出交换后的值
                foreach (var item in array)
                {
                    Console.WriteLine(item);
                }

            }

            //测试
            Employee[] e1 = new Employee[]{
                new Employee("a1",213),
                  new Employee("sad",231),
                    new Employee("gg",56),
                      new Employee("awsdwad",1)
            };

            //调用通用排序方法
            CommonSort<Employee>(e1,Employee.CommonSort);
            Console.ReadKey();

输出结果:

猜你喜欢

转载自blog.csdn.net/weixin_42137574/article/details/104048608