Overview:
Sorting class, which can sort objects of any type, including basic data types;
Object Class, which not only defines data, but also contains sorting details.
Sort class (bubblesorter ):
1 using system; 2 using system. collections. generic; 3 using system. LINQ; 4 using system. text; 5 6 namespace bubblesorter {7 class bubblesorter {8 public static void sort <t> (ilist <t> list, func <t, t, bool> comparison) {9 bool swapped; // identifies whether to perform interactive operations. 10 For (INT I = 0; I <list. count-1; I ++) {11 swapped = false; 12 for (Int J = 0; j <list. count-1-I; j ++) {13 if (comparison (list [J], list [J + 1] ) {14 swap <t> (list, J, J + 1); 15 swapped = true; 16} 17} 18 if (! Swapped) // no interaction is performed. The IDS are sorted. 19 break; 20} 21} 22 23 Private Static void swap <t> (ilist <t> list, int I, Int J) {24 t TMP = list [I]; 25 list [I] = list [J]; 26 List [J] = TMP; 27} 28} 29}
Object class:
1 using system; 2 using system. collections. generic; 3 using system. LINQ; 4 using system. text; 5 6 namespace bubblesorter {7 class employee {8 Public string name {Get; private set;} 9 Public decimal salary {Get; private set ;} 10 11 public employee (string name, decimal salary) {12 name = Name; 13 salary = salary; 14} 15 16 public override string tostring () {17 return string. format ("{0} {1: c}", name, salary); // two decimal places are reserved by default. 18} 19 20 public static bool comparesalary (employee E1, employee E2) {21 return e1.salary <e2.salary; // sort by salary in descending order. 22} 23} 24}
Call class:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace BubbleSorter { 7 class Program { 8 static void Main(string[] args) { 9 Employee[] emplyees = new Employee[]{10 new Employee("Bugs Bunny", 2),11 new Employee("Elmer Fudd", 10),12 new Employee("Daffy Duck", 2.5m),13 new Employee("Wile Coyote", 100.38m),14 new Employee("Foghorn Leghorn", 2.3m),15 new Employee("RoadRunner", 5)16 };17 Console.WriteLine("before sort:");18 foreach (Employee e in emplyees) {19 Console.WriteLine(e);20 }21 22 BubbleSorter.Sort<Employee>(emplyees, Employee.CompareSalary);23 24 Console.WriteLine("after sort:");25 foreach (Employee e in emplyees) {26 Console.WriteLine(e);27 }28 }29 }30 }
Output:
1 before sort: 2 Bugs Bunny ¥2.00 3 Elmer Fudd ¥10.00 4 Daffy Duck ¥2.50 5 Wile Coyote ¥100.38 6 Foghorn Leghorn ¥2.30 7 RoadRunner ¥5.00 8 after sort: 9 Wile Coyote ¥100.3810 Elmer Fudd ¥10.0011 RoadRunner ¥5.0012 Daffy Duck ¥2.5013 Foghorn Leghorn ¥2.3014 Bugs Bunny ¥2.00
Bubblesort-practical Delegation