public static void Main(String[] args) { Hashtable ht = new Hashtable(); List <students> allStudents = new List <students>(); allStudents.Add(new students(1, "john", 29)); allStudents.Add(new students(3, "bob", 28)); allStudents.Add(new students(2, "Andrew", 34)); allStudents.Add(new students(4, "Allen", 19)); allStudents.Add(new students { id = 4, name = "calvin", age = 19 }); // first sort overload no paramter - IComparable allStudents.Sort(); CompareStudents obj = new CompareStudents(); // first sort overload no paramter - IComparer allStudents.Sort(obj); // third sort :we dont want to sort the first one and it is left like that, the remaining 3 will be sorted allStudents.Sort(1, 3, obj); // fourth sort overload my own method to sort . this uses the Comparision delegate Comparison <students> DelegateObj = new Comparison <students>(ComaparisionName); // usually we cannot pass the method name directly as a method name but here we can as it is already defined in the sort() allStudents.Sort(DelegateObj); // or allStudents.Sort(ComaparisionName); // Or use Delegate directly Annonymous methods allStudents.Sort(delegate(students s1, students s2) { return(s1.name.CompareTo(s2.name)); } ); // or just use a lambda expression allStudents.Sort((x, y) => { return(x.name.CompareTo(y.name)); }); }
private bool IsSwapped(CompareStudents compareStudents, bool swapped, int i) { if (compareStudents(_students[i], _students[i + 1])) { var temp = _students[i]; _students[i] = _students[i + 1]; _students[i + 1] = temp; swapped = true; } return(swapped); }
public void Sort(CompareStudents compareStudents) { if (Length == 0) { return; } bool swapped = true; int start = 0; int end = Length; while (swapped) { swapped = false; for (int i = start; i < end - 1; ++i) { swapped = IsSwapped(compareStudents, swapped, i); } if (!swapped) { break; } swapped = false; end -= 1; for (int i = end - 1; i >= start; i--) { swapped = IsSwapped(compareStudents, swapped, i); } start += 1; } }