Kodewick
Start learning →
Patterns: sorting and sorted()46 / 52

Patterns: sorting and sorted()

Lesson 46 of 52 · Part 8 · Sorting · about 28 minutes

This chapter 7 review covers using sorted well, with key, reverse, stability, several keys and cmp_to_key, plus three sorting patterns: sort and then sweep once, custom orderings, and keeping only the top k.

The last five lessons wrote seven sorts, yet at work you almost never write a sort yourself: Python's sorted is Timsort written in C, stable, O(n log n) at worst, and close to O(n) on nearly sorted data. What you really need is two things: first, using sorted well: key, reverse, sorting by several keys, writing a comparison; second, recognising which problems get easy once sorted. Most sorting problems in interviews come down to three patterns: sort, then sweep once from left to right (merging intervals, meeting rooms); sort by a rule of your own (by count, building the largest number); and only the top k, without sorting everything (top K, the k-th largest).

One table for every sort

SortAverageWorstBestExtra spaceStableOne pass fixes
BubbleO(n²)O(n²)O(n)O(1)stablethe largest
SelectionO(n²)O(n²)O(n²)O(1)not stablethe smallest
InsertionO(n²)O(n²)O(n)O(1)stablenothing
Shellabout O(n^1.3)O(n²)O(1)not stablenothing
MergeO(n log n)O(n log n)O(n log n)O(n)stablenothing
QuickO(n log n)O(n²)O(n log n)O(log n)not stablethe pivot
CountingO(n + k)O(n + k)O(n + k)O(k)stable
RadixO(d(n + r))O(d(n + r))O(n + r)stable

To remember: the unstable four are selection, Shell, quick and heap (heap sort, from chapter 4, isn't stable either).

Which to choose:

  • Small (a few dozen) or nearly sorted: insertion sort.
  • Must be stable, or O(n log n) even at worst, or a linked list: merge sort.
  • The general case, speed first, stability not needed: quicksort (random pivot).
  • Whole numbers in a small range: counting sort; fixed number of digits: radix sort.
Choose allPick all that apply

Which sorts are unstable? (You can pick more than one.)

sorted and list.sort

  • sorted(x): works on any iterable (list, tuple, dict, string) and returns a new list, leaving the original alone.
  • a.sort(): lists only, sorts in place and returns None. Saves a copy's worth of memory.

Both take key= and reverse=. key is a function called once per item, and items are compared by what it returns; reverse=True sorts largest first and is still stable: equal items keep their original order, rather than the whole result being sorted and then flipped.

main.py
1words = ["banana", "apple", "Cherry", "date"]2print(sorted(words))                        # capitals sort before lower case3print(sorted(words, key=str.lower))         # ignoring case4print(sorted(words, key=len))               # by length; equal lengths keep their order5print(sorted(words, key=len, reverse=True))6 7a = [3, 1, 2]8print(a.sort(), a)9print(sorted({"b": 2, "a": 1}), sorted("cab"))
Output
['Cherry', 'apple', 'banana', 'date']
['apple', 'banana', 'Cherry', 'date']
['date', 'apple', 'banana', 'Cherry']
['banana', 'Cherry', 'apple', 'date']
None [1, 2, 3]
['a', 'b'] ['a', 'b', 'c']
Guess the outputA wrong guess is fine

Sorting by length, longest first. What does it print?

1words = ["bb", "a", "cc", "d", "eee"]2print(sorted(words, key=len, reverse=True))

Sorting by several keys: score from high to low, and equal scores by name from A to Z. There are two ways.

One is a tuple key: tuples compare by their first item, then by the second on a tie. Score goes high to low and name low to high, opposite directions, so negate the score: key=lambda s: (-s[1], s[0]).

NameScorekey
Dan95(-95, 'Dan')
Amy90(-90, 'Amy')
Cat90(-90, 'Cat')
Bob85(-85, 'Bob')
key = (-score, name): first compare -score (smaller first, so higher scores first); Amy and Cat both have 90, so the name decides

The other is sorting twice: first by the secondary key (name), then by the main key (score). Because the sort is stable, the second sort keeps equal scores in the name order the first one gave. When a string can't be negated (say, names Z to A with scores low to high), this is the easiest way: each sort can take its own reverse.

main.py
1students = [("Cat", 90), ("Bob", 85), ("Dan", 95), ("Amy", 90)]2 3print(sorted(students, key=lambda s: (-s[1], s[0])))4 5by_name = sorted(students, key=lambda s: s[0])            # the secondary key first6print(sorted(by_name, key=lambda s: s[1], reverse=True))  # then the main key7 8print(sorted(students, key=lambda s: s[0], reverse=True))  # names Z to A
Output
[('Dan', 95), ('Amy', 90), ('Cat', 90), ('Bob', 85)]
[('Dan', 95), ('Amy', 90), ('Cat', 90), ('Bob', 85)]
[('Dan', 95), ('Cat', 90), ('Bob', 85), ('Amy', 90)]

Comparison functions: some orders can't be written as one key; you can only say "which of two goes first". For example, joining numbers into the largest possible number: for 3 and 30, "330" > "303", so 3 goes before 30. functools.cmp_to_key turns a comparison function cmp(x, y) (negative if x goes first, positive if it goes after, 0 if equal) into a key:

main.py
1from functools import cmp_to_key2 3def cmp(x, y):4    if x + y > y + x:5        return -1          # x goes first6    if x + y < y + x:7        return 18    return 09 10nums = [3, 30, 34, 5, 9]11strs = sorted(map(str, nums), key=cmp_to_key(cmp))12print(strs, "".join(strs))13print(sorted(map(str, nums), reverse=True))   # plain reverse string order puts 30 before 3: wrong
Output
['9', '5', '34', '3', '30'] 9534330
['9', '5', '34', '30', '3']

When it can be a key, make it a key: a key is computed once per item, while a comparison function calls a Python function on every comparison, which is much slower.

Guess the outputA wrong guess is fine

list.sort sorts in place. What does it print?

1a = [3, 1, 2]2b = a.sort()3print(a, b)

What Timsort is

The algorithm behind sorted and list.sort is Timsort (written for Python by Tim Peters in 2002, later adopted by Java, Android and V8). It is merge sort plus insertion sort, built to exploit how real data is often "sorted in stretches":

  1. Scan once from left to right, cutting out stretches that are already sorted, called runs (strictly descending stretches are reversed in place).
  2. Runs that are too short are extended to minrun (32 to 64 items) with insertion sort: on short stretches insertion sort is fastest (lesson 2).
  3. Runs go onto a stack and are merged in pairs by rules (lesson 3) that keep each pair about the same length. When one side keeps winning during a merge, it skips ahead to search (galloping), saving many comparisons.

So sorted input takes a single scan: 999 comparisons for 1000 numbers; two sorted stretches joined together take one scan and one merge. Here is a simplified version with only steps 1 and 3 (a natural merge sort), counted:

main.py
1cmps = 02 3def find_runs(a):                       # cut into non-decreasing runs4    global cmps5    runs = [[a[0]]]6    for x in a[1:]:7        cmps += 18        if x >= runs[-1][-1]:9            runs[-1].append(x)10        else:11            runs.append([x])12    return runs13 14def merge(left, right):15    global cmps16    out = []17    i = j = 018    while i < len(left) and j < len(right):19        cmps += 120        if left[i] <= right[j]:21            out.append(left[i])22            i += 123        else:24            out.append(right[j])25            j += 126    out.extend(left[i:])27    out.extend(right[j:])28    return out29 30def natural_merge_sort(a):31    if not a:32        return a33    runs = find_runs(a)34    while len(runs) > 1:                # merge in pairs until one run is left35        nxt = [merge(runs[k], runs[k + 1]) for k in range(0, len(runs) - 1, 2)]36        if len(runs) % 2:37            nxt.append(runs[-1])38        runs = nxt39    return runs[0]40 41print(find_runs([3, 5, 8, 1, 2, 9, 4, 6, 7]))42for name, data in [("sorted", list(range(1000))), ("two sorted stretches", list(range(500, 1000)) + list(range(500))), ("mixed", [(i * 7919) % 10007 for i in range(1000)])]:43    cmps = 044    result = natural_merge_sort(data)45    print(name, cmps, result == sorted(data))
Output
[[3, 5, 8], [1, 2, 9], [4, 6, 7]]
sorted 999 True
two sorted stretches 1499 True
mixed 9979 True

Mixed data cuts into very short runs, so this simplified version does about as well as plain merge sort; the real Timsort first extends short runs with insertion sort and merges by its stack rules. Count what the real sorted does with cmp_to_key (this runs the same algorithm as CPython, so the counts are the same):

main.py
1from functools import cmp_to_key2 3count = 04 5def cmp(a, b):6    global count7    count += 18    return a - b9 10inputs = [11    ("sorted", list(range(1000))),12    ("two sorted halves", list(range(0, 1000, 2)) + list(range(1, 1000, 2))),13    ("reversed", list(range(1000, 0, -1))),14    ("mixed", [(i * 7919) % 1009 for i in range(1000)]),15]16for name, data in inputs:17    count = 018    sorted(data, key=cmp_to_key(cmp))19    print(name, count, "comparisons")
Output
sorted 999 comparisons
two sorted halves 1999 comparisons
reversed 999 comparisons
mixed 8628 comparisons

Sorted and reversed input both take one pass (a reversed run is just flipped over); two sorted halves take one pass and one merge; the 1000 mixed numbers take a little over eight thousand, slightly under n log₂ n ≈ 9966.

sorted(x)a.sort()
Works onany iterablelists only
Resulta new listin place, returns None
Memoryan extra O(n)saves that copy
AlgorithmTimsort: stable, O(n log n), O(n) when sortedthe same
Choose one

Timsort (sorted) sorts 1000 numbers that are already sorted. About how many comparisons does it make?

Pattern 1: sort, then sweep once

Many problems need every pair compared when unsorted, O(n²); once sorted, related items sit next to each other, and one sweep from left to right is enough, O(n log n) in all.

The classic is merging intervals: overlapping intervals merge into one. Sorted by start, an interval can only overlap the last one in out: if its start is no later than that one's end, merge them (taking the larger end); otherwise it starts a new interval.

the sorted intervals (left 5 boxes) and out (right 3 boxes)intervalsout1-32-68-109-1215-18012345678

Intervals sorted by start: each is compared only with the last one in out; if its start is no later than that end they merge, otherwise a new one starts
main.py
1def merge_intervals(intervals):2    out = []3    for s, e in sorted(intervals):          # sort by start4        if out and s <= out[-1][1]:5            out[-1][1] = max(out[-1][1], e)6        else:7            out.append([s, e])8    return out9 10print(merge_intervals([[8, 10], [1, 3], [15, 18], [2, 6], [9, 12]]))11 12def min_rooms(meetings):                    # the fewest meeting rooms needed13    events = []14    for s, e in meetings:15        events.append((s, 1))               # a start: +116        events.append((e, -1))              # an end: -117    events.sort()                           # at the same time, -1 sorts before +1: leave before entering18    cur = best = 019    for _, d in events:20        cur += d21        best = max(best, cur)22    return best23 24print(min_rooms([(9, 10), (9, 12), (11, 13), (12, 14)]))
Output
[[1, 6], [8, 12], [15, 18]]
2

The meeting-room problem splits starts and ends into "events", sorts them, and sweeps left to right counting how many are open at once: a sweep line.

aa9–10
bb9–12
cc11–13
dd12–14
89101112131415

min_rooms as a sweep line: the line passes the sorted events in turn, +1 at a start, -1 at an end; the lit ones are the meetings still open. cur peaks at 2

The same "sort + one sweep" also finds duplicates in a list (compare neighbours once sorted), two-sum (two pointers once sorted, chapter 1) and the smallest difference (only neighbours matter once sorted).

Choose one

Merge the intervals [[5, 7], [1, 4], [6, 8], [2, 3]]: sort by start, then scan once. What comes out?

Exercise 1

Merge intervals

Complete merge_intervals(intervals): merge overlapping intervals (touching ends count) and return the result sorted by start.

It should print
[[1, 6], [8, 10], [15, 18]]
[[1, 5]]
[[1, 10]]
[]
exercise1.py
1def merge_intervals(intervals):2    out = []3    # sort by start; if it overlaps out[-1], change its end, otherwise append a new one4    return out5 6print(merge_intervals([[1, 3], [8, 10], [2, 6], [15, 18]]))7print(merge_intervals([[1, 4], [4, 5]]))8print(merge_intervals([[1, 10], [2, 3], [4, 5]]))9print(merge_intervals([]))
Output
Press Run or Ctrl+Enter

Pattern 2: custom orderings

When a problem sets a strange order, write the rule into key. If the rule is "first look at this, then that", make it a tuple; if the rule only compares two at a time, use cmp_to_key.

main.py
1from collections import Counter2 3nums = [4, 1, 2, 2, 3, 3, 3, 4, 4, 4]4cnt = Counter(nums)5print(sorted(nums, key=lambda x: (-cnt[x], x)))            # more frequent first; equal counts, smaller first6 7points = [(3, 4), (1, 1), (-2, 0), (0, 5)]8print(sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2))  # nearest the origin first9 10files = ["img12.png", "img2.png", "img1.png"]11print(sorted(files))                                         # as strings: 12 comes before 212print(sorted(files, key=lambda f: int(f[3:-4])))             # by the number inside13 14order = {"high": 0, "medium": 1, "low": 2}15tasks = [("write docs", "low"), ("fix bug", "high"), ("meeting", "medium"), ("release", "high")]16print(sorted(tasks, key=lambda t: order[t[1]]))              # by a priority of your own
Output
[4, 4, 4, 4, 3, 3, 3, 2, 2, 1]
[(1, 1), (-2, 0), (3, 4), (0, 5)]
['img1.png', 'img12.png', 'img2.png']
['img1.png', 'img2.png', 'img12.png']
[('fix bug', 'high'), ('release', 'high'), ('meeting', 'medium'), ('write docs', 'low')]
Guess the outputA wrong guess is fine

File names are "letter + number"; sort by the letter, then by the number's size. What does it print?

1names = ["b2", "a10", "a2"]2print(sorted(names, key=lambda s: (s[0], int(s[1:]))))
Exercise 2

The largest number

Complete largest_number(nums): join non-negative integers into the largest possible number and return it as a string. Use cmp_to_key: whether x or y goes first depends on which of x + y and y + x is larger. If all are 0, return "0".

It should print
210
9534330
0
12121
exercise2.py
1from functools import cmp_to_key2 3def largest_number(nums):4    strs = [str(x) for x in nums]5    # write cmp(x, y): when x + y is larger, x goes first (return -1)6    return "".join(strs)7 8print(largest_number([10, 2]))9print(largest_number([3, 30, 34, 5, 9]))10print(largest_number([0, 0]))11print(largest_number([121, 12]))
Output
Press Run or Ctrl+Enter

Pattern 3: only the top k

For the 10 largest you don't need all million sorted. Three ways:

  • sorted(a)[:k]: O(n log n), the simplest; use it when n isn't big.
  • heapq.nsmallest(k, a) / nlargest: keep a heap of k (chapter 5), O(n log k); for small k, big data or streams.
  • Quickselect: quicksort's partition, done on one side only. After one partition the pivot lands at index p: if the k-th smallest is on the left, the right side never needs looking at again. O(n) on average.
a72943850123456↑lo↑hi

Finding the 3rd smallest (index 2) in 7 2 9 4 3 8 5: one partition puts the pivot 5 at index 3; 3 > 2, so the search continues on the left only
main.py
1import heapq2 3cmps = 04 5def partition(a, lo, hi):6    global cmps7    p = a[hi]8    i = lo9    for j in range(lo, hi):10        cmps += 111        if a[j] < p:12            a[i], a[j] = a[j], a[i]13            i += 114    a[i], a[hi] = a[hi], a[i]15    return i16 17def quickselect(a, k):                  # the k-th smallest (k from 0); shuffles a18    lo, hi = 0, len(a) - 119    while True:20        p = partition(a, lo, hi)21        if p == k:22            return a[p]23        elif p < k:24            lo = p + 125        else:26            hi = p - 127 28print(quickselect([7, 2, 9, 4, 3, 8, 5], 2))29 30data = [(i * 7919) % 10007 for i in range(1000)]31cmps = 032print("median", quickselect(data[:], 499), sorted(data)[499], "comparisons", cmps)33print(heapq.nsmallest(5, data), sorted(data)[:5])
Output
4
median 5003 5003 comparisons 2870
[0, 9, 19, 28, 38] [0, 9, 19, 28, 38]

Finding the median of 1000 numbers, quickselect made 2870 comparisons; sorting everything takes over 8500. Like quicksort it fears bad pivots (sorted input degenerates to O(n²)), so use a random pivot or median-of-three.

You wantWriteTime
the single largest / smallestmax(a) / min(a)O(n)
the top k, k smallheapq.nlargest(k, a)O(n log k)
the top k, k close to nsorted(a, reverse=True)[:k]O(n log n)
just the k-th smallestquickselectO(n) on average
everything sortedsorted(a) / a.sort()O(n log n)

In interviews: for a sorting problem, first ask yourself "does it get simpler once sorted?": merging intervals, meeting rooms, three-sum and smallest difference are all sort + one sweep. When writing a key, say what stability does for you; for the k-th largest, give the heap's O(n log k) first, then mention quickselect's O(n) on average. Asked which sort Python uses: Timsort, stable, merge plus insertion, exploiting runs that are already sorted.

Choose one

Quickselect is looking for the smallest number (index 0) in 6 1 8 3 5. After one partition around 5, the array is 1 3 5 6 8, with 5 at index 2. Where does it look next?

Exercise 3

The k most frequent words

Complete top_k_words(words, k): return the k words that appear most often, the most frequent first and equal counts in alphabetical order.

It should print
['is', 'the', 'sunny', 'day']
['a', 'b']
['x']
exercise3.py
1from collections import Counter2 3def top_k_words(words, k):4    cnt = Counter(words)5    # sort cnt's keys with the key (-count, word)6    return []7 8print(top_k_words(["the", "day", "is", "sunny", "the", "the", "sunny", "is", "is"], 4))9print(top_k_words(["b", "a", "b", "c", "a"], 2))10print(top_k_words(["x"], 1))
Output
Press Run or Ctrl+Enter

What one pass leaves

The most common long exam question: given an array, what does it look like after one pass (or two) of some sort? Each sort's "pass" does something different; know them and you can write the answer straight down:

SortWhat one pass does5 2 8 1 9 3 after one pass
Bubbleneighbours compared, the largest to the end2 5 1 8 3 9
Selectionthe smallest swapped to the front1 2 8 5 9 3
Insertionthe first two sorted2 5 8 1 9 3
Quick (last as pivot)one partition2 1 3 5 9 8
Choose one

What does 6 3 8 2 5 look like after one pass of bubble sort (compare neighbours, move the bigger one back)?

How you write it at work

A few everyday ways and what they cost:

main.py
1from functools import cmp_to_key2 3rows = [{"name": "Cat", "age": 30}, {"name": "Amy", "age": 25}, {"name": "Bob", "age": 30}]4rows.sort(key=lambda r: (r["age"], r["name"]))     # in place, by age then name5print([r["name"] for r in rows])6 7print(max(rows, key=lambda r: r["age"])["name"])    # just the single largest: max, no sorting8 9pairs = [(2, "b"), (1, "a"), (2, "a")]10print(sorted(pairs))                                # tuples already "compare the first item first"11print(sorted(pairs, key=cmp_to_key(lambda x, y: x[0] - y[0])))   # first item only: ties keep their order
Output
['Amy', 'Bob', 'Cat']
Bob
[(1, 'a'), (2, 'a'), (2, 'b')]
[(1, 'a'), (2, 'b'), (2, 'a')]
  • By default sorted(x, key=...); when the list needn't keep its order, a.sort(key=...) saves a copy.
  • Several keys: a tuple key; with opposite directions and nothing to negate, sort twice (secondary first, then main).
  • key beats cmp_to_key: a key is computed once per item, a comparison function is called on every comparison.
  • For the single largest use max / min, for the top k use heapq, rather than sorting everything and slicing.
  • a.sort() returns None: a = a.sort() loses a; chain with sorted instead.
Choose one

A million records, and you only want the one with the highest age. Which is the right way?

Summary

Take-away

Three sorting patterns

  • sorted returns a new list, a.sort() sorts in place and returns None; both are stable, reverse too
  • Several keys: a tuple key (-score, name), or sort twice, secondary first, then main
  • Orders that only compare two at a time: cmp_to_key; if it can be a key, use a key
  • Sort then sweep (merging intervals, sweep lines); custom keys; top k with heapq or quickselect
  • Timsort: find sorted runs, insertion-sort the short ones, then merge; sorted input is O(n)
1sorted(students, key=lambda s: (-s[1], s[0]))2strs.sort(key=cmp_to_key(cmp))3for s, e in sorted(intervals): ...4heapq.nlargest(k, data)

Chapter 7 quick check

Five questions: selection sort's stability, how many moves insertion sort makes, how many comparisons merge sort makes, quicksort's recursion depth, and counting sort's prefix sums. Work out what each prints yourself, then pick an option.

Guess the outputA wrong guess is fine

Selection sort orders these three records by their first item. What does it print?

1a = [(2, "x"), (2, "y"), (1, "z")]2for i in range(len(a) - 1):3    m = i4    for j in range(i + 1, len(a)):5        if a[j][0] < a[m][0]:6            m = j7    a[i], a[m] = a[m], a[i]8print([name for _, name in a])
Guess the outputA wrong guess is fine

Insertion sort sorts [4, 1, 3, 2]. How many moves does it make in all?

1a = [4, 1, 3, 2]2moves = 03for i in range(1, len(a)):4    key = a[i]5    j = i - 16    while j >= 0 and a[j] > key:7        a[j + 1] = a[j]8        moves += 19        j -= 110    a[j + 1] = key11print(a, moves)
Guess the outputA wrong guess is fine

Merge sort sorts 4 numbers in reverse order. How many comparisons does it make in all?

1cmps = 02 3def merge_sort(a):4    global cmps5    if len(a) <= 1:6        return a7    mid = len(a) // 28    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])9    out, i, j = [], 0, 010    while i < len(left) and j < len(right):11        cmps += 112        if left[i] <= right[j]:13            out.append(left[i])14            i += 115        else:16            out.append(right[j])17            j += 118    return out + left[i:] + right[j:]19 20print(merge_sort([4, 3, 2, 1]), cmps)
Guess the outputA wrong guess is fine

The three-line quicksort with the first item as pivot records how deep the recursion goes. What is it for each input?

1def quick_sort(a, depth=1):2    if len(a) <= 1:3        return a, depth4    p, rest = a[0], a[1:]5    left, d1 = quick_sort([x for x in rest if x < p], depth + 1)6    right, d2 = quick_sort([x for x in rest if x >= p], depth + 1)7    return left + [p] + right, max(d1, d2)8 9print(quick_sort([1, 2, 3, 4, 5, 6])[1], quick_sort([4, 2, 6, 1, 3, 5])[1])
Guess the outputA wrong guess is fine

Count, then use prefix sums to find which box each value starts in. What does it print?

1a = [3, 0, 2, 3, 0]2cnt = [0] * 43for x in a:4    cnt[x] += 15pos = [0] * 46for v in range(1, 4):7    pos[v] = pos[v - 1] + cnt[v - 1]8print(cnt, pos)