Non-comparison Sorts
Sorts that use the digits or range of the keys instead of comparing them.
- Problem: Sorting
- Reorder elements so that their keys are in non-decreasing order under a given comparator.
- Input: A sequence a[0..n-1] of items. Each item has a key. Keys are compared by a total preorder, so equal keys are allowed.
- Output: A permutation of the input in which key(a[i]) <= key(a[i+1]) for every i.
- Constraints
- Model: comparisons only, or access to key digits. Comparison sorts need Ω(n log n) comparisons in the worst case.
- Stability: items with equal keys keep their input order.
- Space: in place, O(log n) stack, or an O(n) buffer.
- Input shape: random, nearly sorted, reversed, many duplicates, or a small integer range.
- Memory model: everything fits in RAM, or data lives on disk or on many machines.
- Cost: comparisons, writes or cache misses.
- Guarantee: a worst-case bound, or a good average case.
- Main idea
- Use the keys themselves as indexes: count them, or distribute them into buckets digit by digit. With small key ranges this runs in linear time.
Counting Sortalgorithm
Count how often each key occurs, turn the counts into positions, and write every value straight to its place. O(n + k) for integer keys below k.
Radix Sortalgorithm
Sort numbers digit by digit with a stable distribution per digit. LSD goes from the last digit to the first, MSD from the first to the last.
Bucket Sortalgorithm
Spread the keys over buckets by value range, sort each small bucket, and join the buckets. Linear on average for evenly spread keys.