Sub topic 3
Timsort: Runs, Merges and Galloping
This chapter assumes you know what a stable sort is, why merge sort is stable and quicksort is not, and what Big-O notation means.
Timsort
Timsort is a stable hybrid of insertion sort and merge sort. It scans the input for runs, which are stretches that are already ascending or strictly descending. It reverses the descending runs. Short runs are extended to a minimum length with insertion sort. Timsort then merges runs from a stack, following rules that keep the merges balanced. During a merge, if one side keeps winning, Timsort switches to galloping: it uses exponential search to find where the next element from the other side goes, then copies the whole block at once. On data that is already partly sorted, Timsort approaches O(n). Its worst case is O(n log n).
Introsort
Introsort starts as quicksort. If the recursion depth goes past about 2·log₂ n, it switches to heapsort, which caps the worst case at O(n log n). Small partitions are finished with insertion sort. None of these steps keeps equal elements in order, so introsort is unstable.
Pattern-Defeating Quicksort
Pattern-defeating quicksort (pdqsort) builds on introsort. It detects input that is already sorted or has many equal keys, and it shuffles some elements when a partition comes out badly unbalanced. It is also unstable.
How Standard Libraries Sort
| Language | Stable | Unstable |
|---|---|---|
| Python | `sorted`, `list.sort` (Timsort) | none |
| Java | `List.sort`, `Arrays.sort` on objects (TimSort) | `Arrays.sort` on primitives (dual-pivot quicksort) |
| C++ | `std::stable_sort` | `std::sort` (usually introsort) |
| JavaScript | `Array.prototype.sort` (stable since ES2019) | none |
| Rust | `sort`, `sort_by_key` | `sort_unstable` (pdqsort-derived) |
| Go | `sort.SliceStable`, `slices.SortStableFunc` | `sort.Slice`, `slices.Sort` (pdqsort) |
What Stability Costs
Stable merge-based sorts usually need O(n) extra memory. Timsort needs up to n/2 extra slots. Unstable sorts run in place with O(log n) stack space and are often faster on random data. Java sorts primitives with an unstable sort because two equal int values cannot be told apart, so stability gives you nothing.
Testing Whether a Sort Is Stable
Tag each element with its input index and sort on the key alone. Among equal keys, the indexes must come out in increasing order. Use few distinct keys so that the data contains many ties.
import random
def is_stable(sort_fn, n=1000, distinct_keys=10):
data = [(random.randrange(distinct_keys), i) for i in range(n)]
result = sort_fn(data, key=lambda pair: pair[0])
return all(
a[1] < b[1]
for a, b in zip(result, result[1:])
if a[0] == b[0]
)
print(is_stable(sorted)) # TrueExercise
In Go, you sort log entries by severity with sort.Slice, and entries with the same severity must stay in time order. What should you change, and why?
Show answer
Call sort.SliceStable instead. sort.Slice uses pdqsort, which is unstable, so entries with equal severity can be reordered. sort.SliceStable keeps them in their input (time) order.