A425 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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?

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 1+2+⋯+(n−1)=n(n−1)/2 comparisons, O(n2). On data that's already nearly sorted, it's fast: about n 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 log2⁡n levels, so merge sort makes about nlog2⁡n 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 O(nlog⁡n) in general and nearly linear on data that's almost sorted.

What sorted data gives you

  • The median and any percentile: the nearest-rank pth percentile of n sorted values is item number ⌈pn/100⌉, counting from 1.
  • Fast search: the bisect module finds where a value belongs in a sorted list in log2⁡n steps, and bisect.insort keeps 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
  1. Insert each item in turn. Compare it with the sorted items to its left, moving each larger one up a place:
ItemCompared withMovesList after
2512 5 4 6 1 3
45, 212 4 5 6 1 3
6502 4 5 6 1 3
16, 5, 4, 241 2 4 5 6 3
36, 5, 4, 231 2 3 4 5 6
  1. Add them up. 1+2+1+4+4=121+1+0+4+3=9 so twelve comparisons and nine moves.
  2. 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).
  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
  1. Split the list. Split into 5, 2, 4 and 6, 1, 3, and again into 5 | 2, 4 and 6 | 1, 3.
  2. 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.
  3. Merge the right half. Merging 1 and 3 takes 1; merging 6 with 1, 3 takes 2, giving 1, 3, 6.
  4. 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.
  5. Add them up. 1+2+1+2+5=11
  6. Compare with insertion sort. That's about the same as insertion sort's 12 for six items. The difference only shows as n 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
  1. 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)
  1. The median. With 20 values it's the average of the 10th and 11th, 11.7 and 12.0: median=11.7+12.02=11.85μs
  2. The 95th percentile. By nearest rank it's the 19th value, 16.7 µs.
  3. 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 n⌈log2⁡n⌉.

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 ⌈pn/100⌉, 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 O(nlog⁡n). Why might insertion sort still be the better choice for a list that's kept sorted as new readings arrive one at a time?

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.