Patterns: sorting and sorted()
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
| Sort | Average | Worst | Best | Extra space | Stable | One pass fixes |
|---|---|---|---|---|---|---|
| Bubble | O(n²) | O(n²) | O(n) | O(1) | stable | the largest |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | not stable | the smallest |
| Insertion | O(n²) | O(n²) | O(n) | O(1) | stable | nothing |
| Shell | about O(n^1.3) | O(n²) | O(1) | not stable | nothing | |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | stable | nothing |
| Quick | O(n log n) | O(n²) | O(n log n) | O(log n) | not stable | the pivot |
| Counting | O(n + k) | O(n + k) | O(n + k) | O(k) | stable | |
| Radix | O(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.
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.
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"))
['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']
Sorting by length, longest first. What does it print?
1words = ["bb", "a", "cc", "d", "eee"]2print(sorted(words, key=len, reverse=True))
reverse=True means "by length, largest first", and equal lengths still keep their original order: bb before cc, a before d. ['eee', 'cc', 'bb', 'd', 'a'] is sorting shortest first and then flipping the whole list, which is not what Python does.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]).
| Name | Score | key |
|---|---|---|
| Dan | 95 | (-95, 'Dan') |
| Amy | 90 | (-90, 'Amy') |
| Cat | 90 | (-90, 'Cat') |
| Bob | 85 | (-85, 'Bob') |
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.
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
[('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:
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
['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.
list.sort sorts in place. What does it print?
1a = [3, 1, 2]2b = a.sort()3print(a, b)
a.sort() sorts a itself and returns None, so b is None. For a new sorted list, use sorted(a).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":
- Scan once from left to right, cutting out stretches that are already sorted, called runs (strictly descending stretches are reversed in place).
- 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).
- 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:
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))
[[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):
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")
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 on | any iterable | lists only |
| Result | a new list | in place, returns None |
| Memory | an extra O(n) | saves that copy |
| Algorithm | Timsort: stable, O(n log n), O(n) when sorted | the same |
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.
i1def 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)]))
[[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.
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).
Merge the intervals [[5, 7], [1, 4], [6, 8], [2, 3]]: sort by start, then scan once. What comes out?
Merge intervals
✓Complete merge_intervals(intervals): merge overlapping intervals (touching ends count) and return the result sorted by start.
[[1, 6], [8, 10], [15, 18]] [[1, 5]] [[1, 10]] []
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([]))
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.
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
[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')]
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:]))))
(letter, number): a10 → ("a", 10), a2 → ("a", 2), b2 → ("b", 2). Letters first, a before b; same letter, then the number, 2 < 10. Only a plain string sort would put a10 before a2.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".
210 9534330 0 12121
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]))
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.
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])
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 want | Write | Time |
|---|---|---|
| the single largest / smallest | max(a) / min(a) | O(n) |
| the top k, k small | heapq.nlargest(k, a) | O(n log k) |
| the top k, k close to n | sorted(a, reverse=True)[:k] | O(n log n) |
| just the k-th smallest | quickselect | O(n) on average |
| everything sorted | sorted(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.
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?
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.
['is', 'the', 'sunny', 'day'] ['a', 'b'] ['x']
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))
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:
| Sort | What one pass does | 5 2 8 1 9 3 after one pass |
|---|---|---|
| Bubble | neighbours compared, the largest to the end | 2 5 1 8 3 9 |
| Selection | the smallest swapped to the front | 1 2 8 5 9 3 |
| Insertion | the first two sorted | 2 5 8 1 9 3 |
| Quick (last as pivot) | one partition | 2 1 3 5 9 8 |
What does 6 3 8 2 5 look like after one pass of bubble sort (compare neighbours, move the bigger one back)?
[2 3 8 6 5] is one pass of selection sort (the smallest, 2, swapped to the front), [3 6 8 2 5] one pass of insertion sort (the first two in order), and [2 3 5 6 8] is fully sorted.How you write it at work
A few everyday ways and what they cost:
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
['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).
keybeatscmp_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 useheapq, rather than sorting everything and slicing. a.sort()returns None:a = a.sort()loses a; chain withsortedinstead.
A million records, and you only want the one with the highest age. Which is the right way?
max is enough: O(n). Sorting is O(n log n) and builds a second list (or scrambles the original order); nlargest(1000, …) keeps 1000 for nothing.Summary
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.
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])
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)
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)
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])
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)
[2, 2, 3, 5] is the prefix sum that includes v itself, which is where each value ends.