委托排序 经典的委托排序(深入分析)
人气:0想了解经典的委托排序(深入分析)的相关内容吗,在本文为您仔细讲解委托排序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:委托排序,c#,下面大家一起来学习吧。
对于数值型的排序我们都已经司空见惯了,但我们有时候希望我们的Sort()方法能够给任何对象排序,比如某段客户机代码包含Currency结构数组或其他的类和结构,就需要对该数组排序。这里我们使用委托并封装这个方法进行比较。
排序我们还是使用经典的冒泡排序,如果数据量较大你可以换为你自己的更高效的排序算法。
先给出整个代码:
复制代码 代码如下:
public class BubbleSorter
{
public static void Sort(object[] sortArray, CompareOperation gtMethod)
{
for (int i = 0; i < sortArray.Length; i++)
{
for (int j = 0; j < sortArray.Length; j++)
{
if (gtMethod(sortArray[j], sortArray[i]))
{
object tmp = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = tmp;
}
}
}
}
}
public class Employee
{
private string name;
private decimal salary;
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}
public override string ToString()
{
return string.Format(name.PadRight(20) + "{0:C}", salary);
}
public static bool RSalaryIsGreater(object lObj, object rObj)
{
Employee lEmployee = lObj as Employee;
Employee rEmployee = rObj as Employee;
return rEmployee.salary > lEmployee.salary;
}
}
再给一个调用示例:
复制代码 代码如下:
public delegate bool CompareOperation(object lObj, object rObj);
class Program
{
static void Main(string[] args)
{
Employee[] employees =
{
new Employee("Tommy",20000),
new Employee("Elmer",10000),
new Employee("Daffy", 25000),
new Employee("Wiley",1000000),
new Employee("Foghorn",23000),
new Employee("RoadRunner",50000),
};
CompareOperation employeeCompareOperation = new CompareOperation(Employee.RSalaryIsGreater);
BubbleSorter.Sort(employees, employeeCompareOperation);
for (int i = 0; i < employees.Length; i++)
{
Console.WriteLine(employees[i].ToString());
}
}
}
加载全部内容