Sorting falls into comparison-based (O(n log n) floor) and non-comparison (counting/radix, O(n+k)). .NET's Array.Sort uses introsort: quicksort with heapsort fallback for worst-case O(n log n). LINQ's OrderBy is stable (preserves equal keys' order). Comparators must be total orders (antisymmetry, transitivity, totality) — never return a - b for numerics. Radix sort excels when key range is small and relative to n.
Choose the right sort for your data characteristics.
Integer subtraction overflows. int.MinValue - 1 = int.MaxValue. Always use x.CompareTo(y) or Compare(x, y).
Sort by secondary key first, then primary key with a stable sort. Equal-primary elements retain secondary order.
Sort 10M records by month (1-12): counting sort is O(n+12). Array.Sort would be O(n log n) — 10x slower.
Sign in to share your feedback and join the discussion.