Classic delegated sorting (in-depth analysis)

Source: Internet
Author: User

We are familiar with numeric sorting, but sometimes we want our Sort () method to Sort any object, for example, if a client code contains an array of Currency structures or other classes and structures, sort the array. Here we use the delegate and encapsulate this method for comparison.

We still use the classic Bubble sorting. If the data size is large, you can replace it with your own more efficient sorting algorithm.

The entire code is provided first:

Copy codeThe Code is as follows: 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;
}
}

Let's give another call example:Copy codeThe Code is as follows: 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 ());
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.