List<T> · C#

Sort

Sorts the list in place with an introspective sort (not stable).

public void Sort(); public void Sort(Comparison<T> comparison)

Complexity

AverageO(n log n)
Worst caseO(n log n)
Extra spaceO(log n) stack

Introsort starts as quicksort, switches to heapsort if recursion gets too deep (bounding the worst case at O(n log n)) and uses insertion sort for small partitions. Equal elements may be reordered.

Tested example

var list = new List<(string Name, int Age)> { ("Ada", 36), ("Bob", 25), ("Cy", 36) };
list.Sort((a, b) => a.Age.CompareTo(b.Age)); // introsort: NOT stable
Assert.Equal("Bob", list[0].Name);
var stable = list.OrderBy(p => p.Age).ToList(); // LINQ OrderBy is stable
Assert.Equal(25, stable[0].Age);
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/ListExamples.cs

Parameters

comparison
Optional ordering; otherwise Comparer<T>.Default.

Behaviour

Returns
Nothing.
Errors and preconditions
InvalidOperationException if the default comparer cannot compare T; the comparison must be a consistent ordering or the result is unspecified.
Changes
Reorders the elements.
Memory and invalidation
In place. Invalidates enumerators.

See it step by step: the Merge sort: split, merge and the auxiliary buffer lesson has an interactive 3D visualizer of the same mechanism.