Hybrid Sorts
Production sorts that combine simple and fast algorithms, such as Timsort and introsort.
- 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 a fast algorithm for large inputs and switch to a simple one, such as insertion sort, for small or nearly sorted parts.
Timsortalgorithm
Find the runs that real data already contains, extend short ones with insertion sort, and merge runs on a stack. Stable, O(n) on sorted input, O(n log n) always.
Introsortalgorithm
Quicksort that watches its recursion depth. Too deep, it switches to heap sort. Small parts go to insertion sort. Fast on average, O(n log n) always.