Week 3 - Sorting A List
Week 3 - Sorting A List
Week 3:
Sorting the elements in a list
Sorting the elements of a list, like last
week we did for an array:
for ( int k=0; k< myList.Count; k++)
{
"find the smallest of the remaining elements";
"swap this smallest element with the k-th element"
}
2
There are several sorting algorithms:
3
The method Sort() of the List-class
(copied from the Microsoft-Help)
Sort() Sorts the elements in the
entire List<T> using the default
comparer.
Sort(Comparison<T>) Sorts the elements in the
entire List<T> using the specified
System.Comparison<T>.
4
The method Sort() of the List-class
(copied from the Microsoft-Help)
Sort() Elements in the list Sorts the elements in the
implement the entire List<T> using the default
IComparable- comparer.
interface
Sort(Comparison<T>) Sorts the elements in the
entire List<T> using the specified
A delegate
System.Comparison<T>.
Comparison
Sort(IComparer<T>) Sorts the elements in the
Something that entire List<T> using the specified
implements the comparer.
IComparer-interface
Sort(Int32, Int32, IComparer Sorts the elements in a range of
<T>) elements in List<T> using the specified
comparer.
5
The method Sort() of the List-class
1. The interface IComparable [ or: IComparable<T> ] has a method:
int CompareTo(Object other)
6
The method Sort() of the List-class
1. The interface IComparable [ or: IComparable<T> ] has a method:
int CompareTo(Object other)
7
1. The default Sort() of the List-class
Suppose we have a list myDrumbles (which is a list of Drumble-objects).
Then:
myDrumbles.Sort();
performs the default sorting method of the list, if the class Drumble
implements one of the IComparable-interfaces
(the “normal” IComparable or, in this case, IComparable<Drumble>).
Demo: show it ! ! !
8
2. Sort-method of the List-class, using a
delegate
Again, suppose we have the list myDrumbles.
Then:
this.myDrumbles.Sort(
new Comparison<Drumble>( XXXX ) );
performs a sorting method of the list, if XXXX is method which fits to the
prototype of the Comparison<Drumble> delegate (or fits to the prototype
of the Comparison delegate).
Demo: show it ! ! !
9
3. Another Sort-method of the List-class,
using an object that implements the
IComparer-interface
Again, suppose we have the list myDrumbles.
Then:
myDrumbles.Sort( ????? );
Demo: show it ! ! !
10