---
title: Sorting
heading: Putting data in order, and what it costs
eyebrow: A4 · Lesson 25 · Sorting
xp: 40
---

::: hook
`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
- [ ] About 1000
- [x] About 10 000
- [ ] About a million

::: reveal
About 10 000. Insertion sort makes about $n^2/4$ comparisons on random data, $2.5 \times 10^{11}$ for a million items, while merge sort makes about $n\log_2 n \approx 2 \times 10^7$. The ratio, $n/(4\log_2 n)$, is about 12 500 and keeps growing with $n$. Lesson 24's table of growth rates in action.
:::
:::

::: nameit
## Sorting in Python

```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:

```python
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 + \cdots + (n - 1) = n(n-1)/2$ comparisons, $O(n^2)$. 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:

```python
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 $\log_2 n$ levels, so merge sort makes about $n\log_2 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(n\log 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 $p$th percentile of $n$ sorted values is item number $\lceil pn/100 \rceil$, counting from 1.
- **Fast search**: the `bisect` module finds where a value belongs in a sorted list in $\log_2 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.
:::

::: example
## Insertion-sort 5, 2, 4, 6, 1, 3. How many comparisons and how many moves does it make?

::: solution
1. **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 |

2. **Add them up.**
   $$\begin{aligned} 1 + 2 + 1 + 4 + 4 &= 12 \\ 1 + 1 + 0 + 4 + 3 &= 9 \end{aligned}$$
   so twelve comparisons and nine moves.
3. **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).
4. **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.
:::
:::

::: example
## Merge-sort the same list, 5, 2, 4, 6, 1, 3. How many comparisons does it make?

::: 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.
:::
:::

::: 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.

::: solution
1. **Sort the measurements.** Then pick values by their rank.

```python
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)
```

2. **The median.** With 20 values it's the average of the 10th and 11th, 11.7 and 12.0:
   $$\begin{aligned} \text{median} &= \frac{11.7 + 12.0}{2} \\ &= 11.85\ \mu\text{s} \end{aligned}$$
3. **The 95th percentile.** By nearest rank it's the 19th value, 16.7 µs.
4. **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
kind: python
given: k = 1..5 int; n = 8 | 20 | 50

## 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` = {n} values, and `c_rev` to the comparisons for the list `list(range(n, 0, -1))`.

```python starter
import random
random.seed(k)
x = [random.randint(0, 999) for _ in range(n)]

def insertion_sort(a):
    return sorted(a), 0

s, c = insertion_sort(x)
c_rev = 0
print(c, c_rev)
```

```python solution
import random
random.seed(k)
x = [random.randint(0, 999) for _ in range(n)]

def insertion_sort(a):
    a, count = list(a), 0
    for j in range(1, len(a)):
        key, i = a[j], j - 1
        while i >= 0:
            count += 1
            if a[i] > key:
                a[i + 1] = a[i]
                i -= 1
            else:
                break
        a[i + 1] = key
    return a, count

s, c = insertion_sort(x)
c_rev = insertion_sort(list(range(n, 0, -1)))[1]
print(c, c_rev)
```

```python tests
import random
random.seed(k)
xs = [random.randint(0, 999) for _ in range(n)]
def ref(a):
    a, cnt = list(a), 0
    for j in range(1, len(a)):
        key, i = a[j], j - 1
        while i >= 0:
            cnt += 1
            if a[i] > key:
                a[i + 1] = a[i]; i -= 1
            else:
                break
        a[i + 1] = key
    return a, cnt
assert s == sorted(xs), "The result should be the sorted list."
assert c == ref(xs)[1], f"For this list insertion sort makes {ref(xs)[1]} comparisons, counting every a[i] > key test, including the last one that stops the slide."
assert c_rev == n * (n - 1) // 2, f"A reversed list of {n} makes n(n-1)/2 = {n * (n - 1) // 2} comparisons."
```

::: right
Right. A reversed list is the worst case, every item sliding past every earlier one: $n(n-1)/2$ comparisons. A random list averages about half that.
:::
:::

::: check
kind: python
given: k = 1..5 int

## 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 starter
import random
random.seed(k)
a = sorted(random.randint(0, 50) for _ in range(random.randint(3, 12)))
b = sorted(random.randint(0, 50) for _ in range(random.randint(3, 12)))

def merge(a, b):
    return a + b

m = merge(a, b)
print(m)
```

```python solution
import random
random.seed(k)
a = sorted(random.randint(0, 50) for _ in range(random.randint(3, 12)))
b = sorted(random.randint(0, 50) for _ in range(random.randint(3, 12)))

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:]

m = merge(a, b)
print(m)
```

```python tests
assert m == sorted(a + b), "The merge should be the two lists' items in sorted order."
tagged = merge([(1, "a"), (2, "a")], [(1, "b"), (3, "b")]) if False else None
assert merge([], [1, 2]) == [1, 2] and merge([3], []) == [3], "When one list runs out, append the rest of the other."
class K:
    def __init__(s, v, t): s.v, s.t = v, t
    def __le__(s, o): return s.v <= o.v
    def __lt__(s, o): return s.v < o.v
    def __gt__(s, o): return s.v > o.v
    def __ge__(s, o): return s.v >= o.v
got = merge([K(1, "a"), K(2, "a")], [K(1, "b"), K(3, "b")])
assert [g.t for g in got] == ["a", "b", "a", "b"], "On a tie take from a first (use <=), which keeps the merge stable."
```

::: right
Right. Each comparison sends one item to the output, so merging $n$ items takes at most $n - 1$ comparisons. Taking from the left list on ties keeps equal items in their original order.
:::
:::

::: check
kind: python
given: k = 1..5 int; n = 10 | 100 | 1000

## 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` = {n} values, and `bound` to $n\lceil\log_2 n\rceil$.

```python starter
import math, random
random.seed(k)
x = [random.random() for _ in range(n)]

def merge_sort(x):
    return sorted(x), 0

s, c = merge_sort(x)
bound = 0
print(c, bound)
```

```python solution
import math, random
random.seed(k)
x = [random.random() for _ in range(n)]

def merge_sort(x):
    if len(x) <= 1:
        return list(x), 0
    m = len(x) // 2
    a, ca = merge_sort(x[:m])
    b, cb = merge_sort(x[m:])
    out, i, j, c = [], 0, 0, 0
    while i < len(a) and j < len(b):
        c += 1
        if a[i] <= b[j]:
            out.append(a[i]); i += 1
        else:
            out.append(b[j]); j += 1
    return out + a[i:] + b[j:], ca + cb + c

s, c = merge_sort(x)
bound = n * math.ceil(math.log2(n))
print(c, bound)
```

```python tests
import math, random
random.seed(k)
xs = [random.random() for _ in range(n)]
def ref(x):
    if len(x) <= 1:
        return list(x), 0
    m = len(x) // 2
    a, ca = ref(x[:m]); b, cb = ref(x[m:])
    out, i, j, c = [], 0, 0, 0
    while i < len(a) and j < len(b):
        c += 1
        if a[i] <= b[j]:
            out.append(a[i]); i += 1
        else:
            out.append(b[j]); j += 1
    return out + a[i:] + b[j:], ca + cb + c
assert s == sorted(xs), "merge_sort should return the sorted list."
assert c == ref(xs)[1], f"Splitting at len(x) // 2 and counting each comparison in each merge gives {ref(xs)[1]}."
assert bound == n * math.ceil(math.log2(n)) and c <= bound, "bound is n * ceil(log2(n)), and the count never exceeds it."
```

::: right
Right. Every level of the recursion merges all $n$ items once, and there are $\lceil\log_2 n\rceil$ levels, so the count stays under $n\lceil\log_2 n\rceil$ for any input, random, sorted or reversed.
:::
:::

::: check
kind: python
given: k = 0..2 int

## 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 starter
parts = [[("0603", 4700, 1), ("0402", 1000, 5), ("0603", 10000, 1), ("0402", 1000, 1), ("0805", 220, 5), ("0603", 4700, 5)],
         [("1206", 1, 1), ("0603", 100, 5), ("0603", 100, 1), ("1206", 10, 1), ("0603", 47, 1)],
         [("0402", 22, 1), ("0402", 22, 5), ("0402", 47, 1), ("0201", 1000, 1), ("0201", 1000, 5), ("0402", 10, 1)]][k]
ordered = sorted(parts)
print(ordered)
```

```python solution
parts = [[("0603", 4700, 1), ("0402", 1000, 5), ("0603", 10000, 1), ("0402", 1000, 1), ("0805", 220, 5), ("0603", 4700, 5)],
         [("1206", 1, 1), ("0603", 100, 5), ("0603", 100, 1), ("1206", 10, 1), ("0603", 47, 1)],
         [("0402", 22, 1), ("0402", 22, 5), ("0402", 47, 1), ("0201", 1000, 1), ("0201", 1000, 5), ("0402", 10, 1)]][k]
ordered = sorted(parts, key=lambda p: (p[0], p[2], -p[1]))
print(ordered)
```

```python tests
want = sorted(parts, key=lambda p: (p[0], p[2], -p[1]))
assert ordered == want, f"The order should be {want}. Negate the resistance in the key to sort it largest first."
```

::: right
Right. A tuple key compares field by field, and negating a number reverses its order within the sort, so one pass handles ascending and descending fields together.
:::
:::

::: check
kind: python
given: k = 1..6 int; p = 50 | 90 | 95 | 99

## Write `percentile(x, p)` returning the nearest-rank `p`th percentile of a list: sort it and take item number $\lceil pn/100 \rceil$, counting from 1. Set `q = percentile(delays, p)` for the starter's 200 delays and `p` = {p}.

```python starter
import math, random
random.seed(k)
delays = [random.expovariate(1 / 12) for _ in range(200)]

def percentile(x, p):
    return sorted(x)[int(p / 100 * len(x))]

q = percentile(delays, p)
print(q)
```

```python solution
import math, random
random.seed(k)
delays = [random.expovariate(1 / 12) for _ in range(200)]

def percentile(x, p):
    s = sorted(x)
    r = math.ceil(p / 100 * len(s))
    return s[max(r, 1) - 1]

q = percentile(delays, p)
print(q)
```

```python tests
import math, random
random.seed(k)
d = sorted(random.expovariate(1 / 12) for _ in range(200))
assert q == d[math.ceil(p / 100 * 200) - 1], f"The {p}th percentile of 200 values is item {math.ceil(p / 100 * 200)} counting from 1, index {math.ceil(p / 100 * 200) - 1}."
assert percentile([3, 1, 2], 100) == 3 and percentile([5, 1, 4, 2, 3], 50) == 3, "Check small cases: the 100th percentile is the largest value, and the 50th of five values is the third."
```

::: right
Right. Rank $\lceil pn/100 \rceil$ counts from 1, so the list index is one less. The starter's `int(...)` is off by one, which matters most for the high percentiles you report latency with.
:::
:::

::: check
given: n = 10 | 50 | 100 | 1000
answer: n*(n - 1)/2
tolerance: 0.1

## Insertion sort is given a list of {n} distinct items in reverse order. How many comparisons does it make?

::: right
Right. Item $j$ slides past all $j - 1$ items before it, comparing with each, so the total is $1 + 2 + \cdots + (\given{n} - 1) = \given{n}(\given{n} - 1)/2$ = {answer}.
:::

::: misses
- [n^2] That counts every item against every item. Each item only compares with the ones before it.
- [n^2/2] Close, but the first item compares with nothing: the sum stops at $\given{n} - 1$.
- [n - 1] That's the best case, an already sorted list, where each item compares once and stays put.
- [any] Not yet. Add up how many items each one slides past: $1 + 2 + \cdots + (\given{n} - 1)$.
:::
:::

::: check
kind: choice

## 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?

- [x] Whichever came first in the original list
- [ ] The one with the alphabetically smaller name
- [ ] It's random
- [ ] Python raises an error on ties

::: right
Right. Python's sort is stable: items with equal keys keep their original order. That's why sorting by a minor key first and then a major key gives the combined order.
:::

::: misses
- [2] The key is only the value, so names play no part.
- [3] Python's sort is deterministic and stable: ties keep their original order.
- [4] Ties are normal and allowed.
:::
:::

::: explain
## Python's built-in sort is $O(n\log 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?

::: model
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 $n$ comparisons, and with `bisect` finding the spot it's $\log_2 n$ comparisons plus the shift. Re-sorting the whole list from scratch costs about $n\log n$ 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

::: check
kind: python
given: k = 0..2 int

## Set `by_len` to the starter's words sorted by length, shortest first, with words of equal length kept in their original order.

```python starter
words = [["volt", "ohm", "farad", "henry", "amp"], ["tesla", "weber", "watt", "joule", "siemens"], ["hz", "kelvin", "mole", "lux", "candela"]][k]
by_len = words
print(by_len)
```

```python solution
words = [["volt", "ohm", "farad", "henry", "amp"], ["tesla", "weber", "watt", "joule", "siemens"], ["hz", "kelvin", "mole", "lux", "candela"]][k]
by_len = sorted(words, key=len)
print(by_len)
```

```python tests
assert by_len == sorted(words, key=len), "Sort with key=len; the sort is stable, so ties keep their order."
```
:::

::: check
kind: python
given: v = 3 | 47 | 150 | 333

## Use `bisect.insort` to add `v` = {v} to the sorted list `xs` so it stays sorted, then set `pos` to the index where it landed using `bisect.bisect_left`.

```python starter
import bisect
xs = [1, 10, 22, 47, 100, 220, 470]
xs.append(v)
pos = len(xs) - 1
print(xs, pos)
```

```python solution
import bisect
xs = [1, 10, 22, 47, 100, 220, 470]
bisect.insort(xs, v)
pos = bisect.bisect_left(xs, v)
print(xs, pos)
```

```python tests
ref = sorted([1, 10, 22, 47, 100, 220, 470] + [v])
assert xs == ref, "insort keeps the list sorted."
assert xs[pos] == v and (pos == 0 or xs[pos - 1] < v), "bisect_left gives the first index holding v."
```
:::
:::
