Sorting and Selection

2 min read

Sorting arranges elements in order. Selection finds the kk-th smallest (or largest) element without fully sorting.

Key algorithms:

AlgorithmTimeSpaceStable?Notes
QuicksortO(nlogn)O(n \log n) avg, O(n2)O(n^2) worstO(logn)O(\log n)NoDefault in most libraries (introsort variant)
MergesortO(nlogn)O(n \log n) alwaysO(n)O(n)YesStable, used when stability matters
HeapsortO(nlogn)O(n \log n) alwaysO(1)O(1)NoIn-place but poor cache behavior
Radix sortO(nk)O(nk)O(n)O(n)YesFor integers/fixed-width keys; kk = key length

Selection without full sort:

  • Quickselect — partitioning-based, O(n)O(n) average for the kk-th element
  • np.argpartition(arr, k) — finds top-kk in O(n)O(n) instead of O(nlogn)O(n \log n) argsort

Where this matters in ML:

  • Top-kk sampling — selecting the kk highest-probability tokens for generation. Quickselect makes this O(V)O(|V|) instead of O(VlogV)O(|V| \log |V|)
  • Top-kk retrieval — ranking candidates by similarity score
  • Argsorttorch.argsort() for ranking predictions, computing rank-based metrics (MRR, NDCG)
  • Non-maximum suppression — sorting bounding boxes by confidence in object detection
  • Sorting networks — differentiable sorting for end-to-end learning (SortNet, NeuralSort)
  • Batching by sequence length — sorting samples to minimize padding waste in NLP

Stability matters when you have a secondary sort criterion — e.g., sorting predictions by score but preserving insertion order for ties.

See also: Big-O and Complexity Analysis, Sampling and Decoding Strategies

Linked from