Sorting arranges elements in order. Selection finds the -th smallest (or largest) element without fully sorting.
Key algorithms:
| Algorithm | Time | Space | Stable? | Notes |
|---|---|---|---|---|
| Quicksort | avg, worst | No | Default in most libraries (introsort variant) | |
| Mergesort | always | Yes | Stable, used when stability matters | |
| Heapsort | always | No | In-place but poor cache behavior | |
| Radix sort | Yes | For integers/fixed-width keys; = key length |
Selection without full sort:
- Quickselect — partitioning-based, average for the -th element
np.argpartition(arr, k)— finds top- in instead of argsort
Where this matters in ML:
- Top- sampling — selecting the highest-probability tokens for generation. Quickselect makes this instead of
- Top- retrieval — ranking candidates by similarity score
- Argsort —
torch.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