Data Structures and Algorithms • C# examples
Sorting Stability, In-Place Behavior, and Comparers
Select a sorting algorithm by its guarantees as well as asymptotic runtime.
Concept
A stable sort preserves the relative order of records with equal keys. In-place describes extra storage, not whether the input changes. Comparers define ordering and must remain consistent; a malformed comparer can break sort assumptions. Production applications should generally use a standard library sort unless a special guarantee is required.
How to approach it
Record stability, worst-case bound, memory, mutability, and comparison cost as part of the choice.
Complexity
Comparison sorting has a general Ω(n log n) lower bound; specialized key domains may allow other bounds.
C# example
var people = records
.OrderBy(person => person.LastName, StringComparer.Ordinal)
.ThenBy(person => person.FirstName, StringComparer.Ordinal)
.ToArray();
Expected result or behavior
The secondary key makes tie ordering explicit instead of relying on input order.
Practice exercise
Define a comparer for case-insensitive identifiers and test equal values consistently.
Key takeaway: Correct ordering semantics matter as much as the algorithm’s speed.