Lesson 1 of 4
How sorting works
Two sorts built from the walk you already know. Insertion sort grows a sorted front and costs O(n²). Merge sort splits a list into single items and merges them back in O(n log n). Then Python's own sort, and why so many solutions start by sorting.
Trace insertion sort and count its comparisons on sorted and reversed input
Merge two sorted lists in one pass with two pointers
Explain why merge sort makes about log n levels of n steps each, and write it
Sort records with key= and say what a stable sort keeps
Sort first to put related items side by side, then solve the problem in one walk
A nightly job hands you yesterday's orders in the order the servers sent them, not in time order. In SQL you write ORDER BY; in Python, sorted(orders). One line, and the right line at work.
In an interview, two questions hide behind that line. What does the sort cost, and why? And could you write one yourself? LeetCode 912 asks exactly that. Sorting is also the first line of many solutions, because a sorted list puts related items next to each other.
This lesson builds two sorts from the walk you know, a slow one and a fast one, then opens Python's own and uses it as the first step of a walk.
Insertion sort: grow a sorted front
How do you sort a hand of cards? You keep the cards you hold in order. You take the next card and slide it left until the card on its left is not bigger. Insertion sort does exactly that to a list.
Two words first. The sorted part is the stretch at the front that is already in order; it starts as the first item alone. A pass takes the next item after it and swaps it left, one neighbor at a time, while the left neighbor is bigger.
The figure runs insertion sort on [5, 2, 4, 1, 3]. Each step compares the current item (blue) with its left neighbor and either swaps them or places it. The sorted part is lime, and the readouts count comparisons and swaps. Guess first: how many times will the 1 swap?
Every walk in this course keeps a promise: a fact about its notebook that is true after every pass. The promise of insertion sort: after the pass for index i, the items at indexes 0 to i are in order. For a list of n items the last pass is for index n − 1, so when it ends, the whole list is in order.
Here is the same walk in Python, on the same list. i is the index of the item this pass places, and j follows that item left. Line 5 swaps with unpacking from module 1: a, b = b, a. Guess first: how many times does line 4 run in the pass that places the 1?
def insertion_sort(nums):for i in range(1, len(nums)):j = iwhile j > 0 and nums[j - 1] > nums[j]:nums[j - 1], nums[j] = nums[j], nums[j - 1]j -= 1return nums
(nothing printed yet)What does it cost? The item for index i can move left at most i places, one comparison per place, so its pass makes at most i comparisons. Largest first, every pass goes all the way to the front: 1 + 2 + 3 + 4 = 10 for 5 items, the figure's Reversed number. In general that is 1 + 2 + ... + (n − 1) = n(n − 1)/2, about n2/2, so O(n2). Check it on 5 items: 5 × 4 / 2 = 10. For 100,000 items that is about 5 billion comparisons: over 8 minutes at module 2's rule of thumb of 10 million simple steps a second.
On a sorted list, each pass makes one comparison and stops: n − 1 in all, the figure's 4. So insertion sort is quick on nearly sorted lists and slow on long lists that are not.
This is insertion sort with one extra line: it prints the list at the end of every pass. Type exactly what it prints.
nums = [6, 2, 5, 1]
for i in range(1, len(nums)):
j = i
while j > 0 and nums[j - 1] > nums[j]:
nums[j - 1], nums[j] = nums[j], nums[j - 1]
j -= 1
print(nums)
Insertion sort runs on [6, 5, 4, 3, 2, 1]. Count a comparison every time the while line compares two neighbors (a pass that reaches index 0 makes no comparison there). How many comparisons does the whole sort make?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Merging two sorted lists
What if half the work were already done? Suppose you hold two sorted lists, left = [2, 5, 8] and right = [3, 4, 9]. The smallest item of all is one of the two front items, because each front item is the smallest of its own list. Take the smaller, and the same question repeats with one item fewer.
The walk keeps two pointers, one per list (module 4: a pointer is an index that moves along the data). i is the index of the next unused item in left, and j the next unused item in right. out is the merged list so far. When one list runs out, the rest of the other is at least as big as all of out, so it goes on the end in one piece: out.extend(more) appends every item of more to out, in order. Guess first: which list runs out first, and what is left over?
def merge(left, right):out = []i = 0j = 0while i < len(left) and j < len(right):if left[i] <= right[j]:out.append(left[i])i += 1else:out.append(right[j])j += 1out.extend(left[i:])out.extend(right[j:])return out
(nothing printed yet)The promise: out always holds the smallest len(out) items of the two lists, in order. Each append takes the smallest unused item, so the promise survives every step. Each step writes one item, so merging n items takes O(n) time. On a tie, <= takes the left item first, which keeps equal items in their starting order.
Now put the merge together yourself. This version adds the leftovers in its last line.
Put the lines in order to build merge(left, right), which takes two sorted lists and returns one sorted list with all their items. Indentation is part of each line. Two lines do not belong.
This version sets all three names on one line, and its last line adds the leftovers of both lists: one of the two slices left[i:] and right[j:] is always empty by then.
Add lines from the list below, in order.
return out + left[i:] + right[j:]def merge(left, right):j += 1while i < len(left) or j < len(right):while i < len(left) and j < len(right):out.append(left[i])out, i, j = [], 0, 0out.append(right[j])i += 1return outif left[i] <= right[j]:else:
The two leftover lines look like an afterthought. Leave them out and see what goes missing.
This merge has no lines for the leftovers:
def merge(left, right):
out = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
return out
What does merge([1, 5], [2, 3]) return?
Choose one answer, then check.
Merge sort: halve, then merge
A merge needs two sorted lists. Where do they come from? A list of one item is already sorted. So merge sort splits the list in half, again and again, until every piece holds one item. Then it merges the pieces back in pairs: single items into sorted pairs, pairs into sorted fours, up to the whole list.
The figure runs merge sort on 8 items. The top of the drawing shows the splits, one level per step. The bottom shows the merges, one comparison or one copy per step: i is blue in the left half, j is teal in the right half, and an item written to the output turns lime. Guess first: how many items does each merge level write?
Every merge level writes all 8 items once, and each write costs at most one comparison. There are 3 levels, because 8 halves to 4, 2, 1 in three steps. In general there are about log n levels: how many times n can be halved before reaching 1 (module 2). About log n levels of n steps each: O(n log n). For 100,000 items that is 17 levels, about 1.7 million steps instead of 5 billion.
How does code split a list again and again? With a function that calls itself on each half. Module 2 named this: a recursive function (module 8 teaches recursion properly). It needs a base case, an input small enough to answer without calling itself, so the calls stop. Here that is a list of 0 or 1 items.
The trace splits [7, 2, 9, 4] and prints each piece with its depth, the number of halvings that made it. The viewer draws one box per call that has started and not finished. Guess first: is [9, 4] printed before or after [7]?
def split(nums, depth):print(depth, nums)if len(nums) <= 1:returnmid = len(nums) // 2split(nums[:mid], depth + 1)split(nums[mid:], depth + 1)
(nothing printed yet)Merge sort is this function with one change: each call hands back its piece sorted. A piece of one item comes back as it is. A bigger piece calls itself on its two halves and merges the two sorted lists it gets back. Trust the two calls to hand back sorted halves; the merge does the rest. Code written this way finishes the whole left side before it touches the right, as the split trace did, while the figure worked level by level. The pieces and the merges are the same; only their order differs.
Work one by hand before you write it. Five items split unevenly, which the merge does not mind.
On paper, run merge sort on [6, 3, 8, 1, 5]. The left half always gets len // 2 items. Draw the splits as a tree, then do the merges from the bottom up, and count every comparison of two items. A merge that copies the rest of one half makes no comparison for that copy.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Merge sort runs on a list of 1,000 items, splitting the left half off with len // 2 each time. How many levels of splitting does it take until every piece holds one item? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
So far: insertion sort grows a sorted front, O(n2). Merging two sorted lists is one pass. Merge sort halves down to single items and merges back up: about log n levels of n steps, O(n log n).
Now write it. You have both parts, the split from the trace and the merge from the puzzle; the problem joins them in one function, without sorted.
Two tests catch the common slips. The empty list: with a base case of exactly 1 item, [] splits into [] and [] forever, until Python raises RecursionError. And [1, 2, 9, 8]: its last merge uses up [1, 2] before it takes anything from [8, 9], so the whole right half must come from the leftover lines. On the large test, 18,000 numbers in reverse order, insertion sort would make about 162 million comparisons; merge sort makes at most 15 levels × 18,000 = 270,000.
Python's sort: sorted, key and stability
When sorting is only one step of a solution, call sorted(nums) (it returns a new sorted list) or nums.sort() (it sorts nums itself and returns None). Underneath runs Timsort, a mix of merge sort and insertion sort. It finds stretches already in order, called runs, lengthens short runs with insertion sort, and merges runs the way merge sort does. It is O(n log n) in the worst case, and on a sorted list it finds one run and stops after about n comparisons.
It is also stable: items that tie keep the order they had before the sort. Module 1 sorted words with key=len: a key is a function Python calls once on each item, and it then sorts by those results instead of by the items. The trace sorts orders by amount, and two orders tie. Guess first: does "ana" come before or after "cy"?
orders = [("cy", 30), ("bo", 10), ("ana", 30), ("di", 20)]def amount(order):return order[1]by_amount = sorted(orders, key=amount)print(by_amount)
(nothing printed yet)You will usually write the key as a lambda, a one-line function with no name: key=lambda order: order[1] does the same as amount. The name before the colon is the parameter; the expression after it is the result. Two more forms come up often:
- Several fields: return a tuple.
key=lambda order: (order[1], order[0])sorts by amount, then by name among equal amounts. Python compares tuples item by item, and the second item counts only when the first items are equal. - Largest first:
reverse=True. Items with equal keys still keep their starting order.
Run both on the same orders. Guess first where "ana" and "cy" land in each line.
The tuple key breaks the tie by name, so the first line has "ana" before "cy". With reverse=True the 30s come first and keep their starting order: ('cy', 30), then ('ana', 30).
Type exactly what this prints. The key is a lambda: it returns the second item of each tuple.
people = [("max", 3), ("ng", 1), ("kim", 3), ("lee", 1)]
for name, team in sorted(people, key=lambda p: p[1]):
print(name, team)
Sort first, then walk
Why do so many solutions start with a sort? After sorting, items that belong together sit side by side. Equal values become neighbors, the closest pair of numbers is a pair of neighbors (module 2), and meetings line up by start time (the intervals lesson). A question about every pair, O(n2), often becomes a question about each item and its left neighbor: one walk.
The trace answers "does any value appear twice?" this way; module 3 used a set. Guess first: at which i does the walk stop?
def has_duplicate(nums):ordered = sorted(nums)for i in range(1, len(ordered)):if ordered[i] == ordered[i - 1]:return Truereturn False
(nothing printed yet)The promise: before checking index i, no two neighbors among indexes 0 to i − 1 are equal. In a sorted list equal values are neighbors, so no value repeats in that stretch. A walk that ends without a match proves nothing repeats.
The set from module 3 is faster: O(n) time, O(n) space. But the follow-up "use less memory" now has an answer: sort in place with nums.sort() and walk, with no set and no copy. That changes the caller's list, so ask first. Python's sort still borrows temporary room for up to about n/2 items while it merges, so say "no set and no copy", not O(1) space. And when the question is about order (closest values, runs, overlaps), the sort is the whole idea.
The exercise uses the same walk with three notebook values, one more than the longest streak in module 1: the length of the current run of equal values, the longest run so far, and that run's value.
Write most_common(nums), which returns the value that appears most often in a non-empty list. On a tie, return the smallest of the tied values. Do it the sorting way: sort a copy so equal values sit side by side as runs, then walk once. No dict, set or Counter. Leave nums unchanged.
raise NotImplementedError, then press Run tests. Each check says what it expects.This module's problem list has one more from this family: meeting rooms (LeetCode 252), which sorts meetings by start time and compares each with the one before it.
Last, say it the way you would in the room.
An interviewer asks you to sort a list of integers without sorted. Before you type, explain merge sort: the walk, the notebook, the promise and the cost. Include why it is O(n log n) and not O(n2).
Saved in this browser as you type.