A4 · Lesson 25 · Sorting
Putting data in order, and what it costs
sorted(x) puts a million readings in order in a fraction of a second, so why learn how? Because the way a sort works decides what it costs, and the difference is enormous: the simple method you'd invent by hand takes hours on the same million readings. Sorting also does more than order a list. It finds medians and percentiles, lines up two logs by time, and ranks parts by several fields at once, and those jobs depend on details like what happens to items that tie.
Predict
For a million readings in random order, about how many times more comparisons does insertion sort make than merge sort?
About 10 000. Insertion sort makes about comparisons on random data, for a million items, while merge sort makes about . The ratio, , is about 12 500 and keeps growing with . Lesson 24's table of growth rates in action.
Name it
Sorting in Python
sorted(x) # a new sorted list; x is unchanged
x.sort() # sorts x in place, returns None
sorted(x, reverse=True) # largest first
sorted(parts, key=lambda p: p[2]) # sort by a computed key
sorted(parts, key=lambda p: (p[0], -p[1])) # by field 0, then field 1 descending
Python's sort is stable: items whose keys tie keep the order they had before. That's what makes a two-pass sort work, sorting by the minor key first and then the major one.
Insertion sort
Take each item in turn and slide it left past every larger item already sorted:
def insertion_sort(a):
a = list(a)
for j in range(1, len(a)):
key, i = a[j], j - 1
while i >= 0 and a[i] > key:
a[i + 1] = a[i]
i -= 1
a[i + 1] = key
return a
Each item may move past all the ones before it, so the worst case (reverse order) makes comparisons, . On data that's already nearly sorted, it's fast: about comparisons. It's the method of choice for short or almost-sorted lists.
Merge sort
Split the list in half, sort each half the same way, then merge the two sorted halves by repeatedly taking the smaller front item:
def merge(a, b):
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]
def merge_sort(x):
if len(x) <= 1:
return x
m = len(x) // 2
return merge(merge_sort(x[:m]), merge_sort(x[m:]))
Merging is linear, and halving takes levels, so merge sort makes about comparisons whatever the input. Taking from the left half on ties (<=) is what keeps it stable. Python's own sort, Timsort, merges runs of already-ordered data, so it's in general and nearly linear on data that's almost sorted.
What sorted data gives you
- The median and any percentile: the nearest-rank th percentile of sorted values is item number , counting from 1.
- Fast search: the
bisectmodule finds where a value belongs in a sorted list in steps, andbisect.insortkeeps a list sorted as items arrive. - Duplicates and gaps sit next to each other, so one pass finds them.
Worked example
Insertion-sort 5, 2, 4, 6, 1, 3. How many comparisons and how many moves does it make?
Show the solution
- Insert each item in turn. Compare it with the sorted items to its left, moving each larger one up a place:
| Item | Compared with | Moves | List after |
|---|---|---|---|
| 2 | 5 | 1 | 2 5 4 6 1 3 |
| 4 | 5, 2 | 1 | 2 4 5 6 1 3 |
| 6 | 5 | 0 | 2 4 5 6 1 3 |
| 1 | 6, 5, 4, 2 | 4 | 1 2 4 5 6 3 |
| 3 | 6, 5, 4, 2 | 3 | 1 2 3 4 5 6 |
- Add them up. so twelve comparisons and nine moves.
- Count the inversions. The nine moves are exactly the list's inversions, the pairs that are out of order: (5, 2), (5, 4), (5, 1), (5, 3), (2, 1), (4, 1), (4, 3), (6, 1) and (6, 3).
- What that means. Each move fixes one inversion, which is why insertion sort is quick on nearly sorted data, which has few of them.
Answer twelve comparisons and nine moves.
Worked example
Merge-sort the same list, 5, 2, 4, 6, 1, 3. How many comparisons does it make?
Show the solution
- Split the list. Split into 5, 2, 4 and 6, 1, 3, and again into 5 | 2, 4 and 6 | 1, 3.
- Merge the left half. Merging 2 and 4 takes 1 comparison; merging 5 with 2, 4 takes 2 (5 against 2, then 5 against 4), giving 2, 4, 5.
- Merge the right half. Merging 1 and 3 takes 1; merging 6 with 1, 3 takes 2, giving 1, 3, 6.
- Merge the halves. 2 vs 1 (take 1), 2 vs 3 (take 2), 4 vs 3 (take 3), 4 vs 6 (take 4), 5 vs 6 (take 5), then 6 is left over: 5 comparisons.
- Add them up.
- Compare with insertion sort. That's about the same as insertion sort's 12 for six items. The difference only shows as grows: for a thousand items, about 10 000 against 250 000.
Answer merge sort makes 11 comparisons.
Worked example
Twenty delay measurements, in µs, are 12.1, 9.8, 15.2, 11.0, 30.5, 10.4, 12.9, 11.7, 13.3, 10.9, 14.8, 11.2, 9.9, 12.0, 16.7, 10.1, 11.5, 12.4, 13.9 and 11.1. Find the median and the 95th percentile.
Show the solution
- Sort the measurements. Then pick values by their rank.
import math
d = sorted([12.1, 9.8, 15.2, 11.0, 30.5, 10.4, 12.9, 11.7, 13.3, 10.9,
14.8, 11.2, 9.9, 12.0, 16.7, 10.1, 11.5, 12.4, 13.9, 11.1])
median = (d[9] + d[10]) / 2 # 11.85
p95 = d[math.ceil(0.95 * len(d)) - 1] # the 19th value: 16.7
print(median, p95)
- The median. With 20 values it's the average of the 10th and 11th, 11.7 and 12.0:
- The 95th percentile. By nearest rank it's the 19th value, 16.7 µs.
- The outlier. The 30.5 µs outlier pulls the mean up to 13.1 µs but leaves both of these alone, which is why latency is usually reported as percentiles.
Answer the median is 11.85 µs and the 95th percentile 16.7 µs.
Check
Write insertion_sort(a) returning a new sorted list and the number of comparisons it made, as (result, comparisons), counting each a[i] > key test. Set s, c = insertion_sort(x) for the starter's random list of n = 8 values, and c_rev to the comparisons for the list list(range(n, 0, -1)).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write merge(a, b) that merges two sorted lists into one sorted list in a single pass, taking from a when the front items tie, without calling sort or sorted. Set m = merge(a, b) for the starter's lists.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Using your merge, write the recursive merge_sort(x) and count the comparisons it makes in total. Set s, c = merge_sort(x) for the starter's random list of n = 10 values, and bound to .
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Each part in the starter is (package, ohms, tolerance_pct). Set ordered to the list sorted by package alphabetically, then by tolerance from tightest to loosest, then by resistance from largest to smallest, using one call to sorted with a tuple key.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write percentile(x, p) returning the nearest-rank pth percentile of a list: sort it and take item number , counting from 1. Set q = percentile(delays, p) for the starter's 200 delays and p = 50.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Insertion sort is given a list of 50 distinct items in reverse order. How many comparisons does it make?
Check
You sort a parts list by value with sorted(parts, key=lambda p: p.value). Two parts have the same value. Which comes first in the result?
Explain why
Python's built-in sort is . Why might insertion sort still be the better choice for a list that's kept sorted as new readings arrive one at a time?
When the list is already sorted and one new item arrives, only that item is out of place, so insertion sort's single slide costs at most comparisons, and with bisect finding the spot it's comparisons plus the shift. Re-sorting the whole list from scratch costs about every time. Insertion sort's cost depends on how disordered the data is, and data that arrives into an already sorted list is barely disordered at all. Big-O describes the worst case over all inputs, not the case you actually have.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.