探討如何用委托處理排序
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class 冒泡排序
{
//首先要了解冒泡排序,其實(shí)很簡(jiǎn)單就是索引前面的跟后面的比較,如果比后面的大2個(gè)值的位置就進(jìn)行調(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();
//冒泡算法中第一個(gè)參數(shù)是對(duì)應(yīng)Employees數(shù)組信息,第二個(gè)參數(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);
}
//定義一個(gè)方法,如果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;
}
}
}
}
}
}
相關(guān)文章
C#實(shí)現(xiàn)的簡(jiǎn)單驗(yàn)證碼識(shí)別實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)的簡(jiǎn)單驗(yàn)證碼識(shí)別實(shí)例,只適應(yīng)一些簡(jiǎn)單的驗(yàn)證碼,需要的朋友可以參考下2014-06-06C#?彈出窗口show()和showdialog()的兩種方式
本文主要介紹了C#?彈出窗口show()和showdialog()的兩種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07C#使用Json.Net對(duì)JSON與對(duì)象的序列化與反序列化
這篇文章介紹了Json.Net對(duì)JSON與對(duì)象的序列化與反序列化,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法
這篇文章主要介紹了C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法,涉及C#針對(duì)數(shù)組的遍歷、校驗(yàn)及排序等操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08如何使用C#修改本地Windows系統(tǒng)時(shí)間
這篇文章主要介紹了如何使用C#修改本地Windows系統(tǒng)時(shí)間,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01