经典的委托排序(深入分析)
程序员文章站
2023-12-22 16:46:16
对于数值型的排序我们都已经司空见惯了,但我们有时候希望我们的sort()方法能够给任何对象排序,比如某段客户机代码包含currency结构数组或其他的类和结构,就需要对该数...
对于数值型的排序我们都已经司空见惯了,但我们有时候希望我们的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());
}
}
}