探討如何用委托處理排序
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class 冒泡排序
{
//首先要了解冒泡排序,其實很簡單就是索引前面的跟后面的比較,如果比后面的大2個值的位置就進行調(diào)換
static void Main()
{
int[] str ={ 0, 14, 3, 6, 1, 30, 10, 9, 28 };
for (int i = 0; i < str.Length; i++)
{
for (int j = i + 1; j < str.Length; j++)
{
if (str[j] < str[i])
{
int index = str[i];
str[i] = str[j];
str[j] = index;
}
}
}
for (int m = 0; m < str.Length; m++)
{
Console.WriteLine(str[m]);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public delegate bool DelegateTest(object obj1, object obj2);
class Class1
{
static void Main()
{
Employee[] Employees =
{
new Employee("huguo",1000000),
new Employee("lili",20000),
new Employee("lulu",30000),
new Employee("xixi",50000),
new Employee("jianjian",10000),
new Employee("yoyo",9000)
};
//委托DelegateTest代理的方法是Greate
DelegateTest MyTest = new DelegateTest(Employee.Greate);
Sorter MySort = new Sorter();
//冒泡算法中第一個參數(shù)是對應Employees數(shù)組信息,第二個參數(shù)是委托
MySort.Sort(Employees, MyTest);
for (int m = 0; m < Employees.Length; m++)
{
Console.WriteLine(Employees[m].ToString());
}
}
}
class Employee
{
public string Name;
public int Salary;
public Employee(string Name, int Salary)
{
this.Name = Name;
this.Salary = Salary;
}
//用override重寫string方法
public override string ToString()
{
return string.Format(Name + ",{0:C},", Salary);
}
//定義一個方法,如果obj2傳過來的 Salary大于obj1就返回true;
public static bool Greate(object obj1, object obj2)
{
Employee Employee1 = (Employee)obj1;
Employee Employee2 = (Employee)obj2;
return (Employee2.Salary > Employee1.Salary) ? true : false;
}
}
class Sorter
{
public void Sort(object[] ArrayObj, DelegateTest Test)
{
//下面就是冒泡算法啦
for (int i = 0; i < ArrayObj.Length; i++)
{
for (int j = i + 1; j < ArrayObj.Length; j++)
{
if (Test(ArrayObj[j], ArrayObj[i]))
{
object Temp = ArrayObj[i];
ArrayObj[i] = ArrayObj[j];
ArrayObj[j] = Temp;
}
}
}
}
}
}
相關文章
C#?彈出窗口show()和showdialog()的兩種方式
本文主要介紹了C#?彈出窗口show()和showdialog()的兩種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07