I understand there's a difference between the sorting algorithms in List<T>.Sort
and Enumerable.OrderBy
. The latter is stable, meaning where elements are equal, it preserves their original order.
It's all very well repeating the definition, but to teach this, I'd like to demonstrate a simple example where the algorithms differ in results.
I found came up with this example "Given the seven Weasley siblings from oldest to youngest, sort them by name length".
var weasleys = new List<string>{"Bill", "Charlie", "Percy", "Fred", "George", "Ron", "Ginny"};
In this case, OrderBy
weasleys.OrderBy(x => x.Length)
gives [Ron, Bill, Fred, Percy, Ginny, George, Charlie]. Note that 'Bill' and 'Fred' are the same length but Bill is older so Bill comes first.
Whereas List.Sort
weasleys.Sort((x, y) => x.Length.CompareTo(y.Length));
gives [Ron, Fred, Bill, Ginny, Percy, George, Charlie].
My example had seven items. Is there a simpler case with fewer items? What's the smallest list on which the algorithms give different results?