zl程序教程

您现在的位置是:首页 >  后端

当前栏目

探讨如何用委托处理排序

排序 如何 处理 探讨 委托
2023-06-13 09:15:01 时间

复制代码代码如下:


usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;

namespaceConsoleApplication1
{
   class冒泡排序
   {
       //首先要了解冒泡排序,其实很简单就是索引前面的跟后面的比较,如果比后面的大2个值的位置就进行调换
       staticvoidMain()
       {
           int[]str={0,14,3,6,1,30,10,9,28};
           for(inti=0;i<str.Length;i++)
           {
               for(intj=i+1;j<str.Length;j++)
               {
                   if(str[j]<str[i])
                   {
                       intindex=str[i];
                       str[i]=str[j];
                       str[j]=index;
                   }
               }
           }
           for(intm=0;m<str.Length;m++)
           {
               Console.WriteLine(str[m]);
           }
       }
   }
}


复制代码代码如下:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;

namespaceConsoleApplication1
{
   publicdelegateboolDelegateTest(objectobj1,objectobj2);
   classClass1
   {
       staticvoidMain()
       {
           Employee[]Employees=
             {
                 newEmployee("huguo",1000000),
                 newEmployee("lili",20000),
                 newEmployee("lulu",30000),
                 newEmployee("xixi",50000),
                 newEmployee("jianjian",10000),
                 newEmployee("yoyo",9000)
             };
           //委托DelegateTest代理的方法是Greate
           DelegateTestMyTest=newDelegateTest(Employee.Greate);
           SorterMySort=newSorter();
           //冒泡算法中第一个参数是对应Employees数组信息,第二个参数是委托
           MySort.Sort(Employees,MyTest);
           for(intm=0;m<Employees.Length;m++)
           {
               Console.WriteLine(Employees[m].ToString());
           }
       }
   }
   classEmployee
   {
       publicstringName;
       publicintSalary;
       publicEmployee(stringName,intSalary)
       {
           this.Name=Name;
           this.Salary=Salary;
       }
       //用override重写string方法
       publicoverridestringToString()
       {
           returnstring.Format(Name+",{0:C},",Salary);
       }
       //定义一个方法,如果obj2传过来的Salary大于obj1就返回true;
       publicstaticboolGreate(objectobj1,objectobj2)
       {
           EmployeeEmployee1=(Employee)obj1;
           EmployeeEmployee2=(Employee)obj2;
           return(Employee2.Salary>Employee1.Salary)?true:false;
       }
   }
   classSorter
   {
       publicvoidSort(object[]ArrayObj,DelegateTestTest)
       {
           //下面就是冒泡算法啦
           for(inti=0;i<ArrayObj.Length;i++)
           {
               for(intj=i+1;j<ArrayObj.Length;j++)
               {
                   if(Test(ArrayObj[j],ArrayObj[i]))
                   {
                       objectTemp=ArrayObj[i];
                       ArrayObj[i]=ArrayObj[j];
                       ArrayObj[j]=Temp;
                   }
               }
           }
       }
   }

}