Sub topic 2
Merging Two Sorted Lists in Linear Time
This chapter assumes you can write Python functions with loops, index into lists, and read Big-O notation. You do not need recursion yet. The merge step has none, and it is the part of merge sort that does the actual sorting work.
Merge sort spends most of its time in one operation. It takes two lists that are already sorted and combines them into one sorted list. If this operation is fast and correct, the rest of the algorithm is mostly bookkeeping. This chapter covers how the merge works, why it runs in linear time, the edge cases that cause most bugs, and an index-based version that later chapters build on.
The Problem
The input is two sequences, left of length m and right of length n. Each is sorted in non-decreasing order. The output is one sequence of length m + n that contains every element of both inputs, also in non-decreasing order.
You could concatenate the lists and sort the result, but that throws away what you already know. Because both inputs are sorted, the smallest remaining element overall must be at the front of one of the two lists. You only ever need to look at two candidates.
The Two-Pointer Idea
Keep one index into each list. i points at the first element of left not yet used, and j does the same for right. At each step:
- Compare
left[i]withright[j]. - Append the smaller one to the output and advance its index.
- Repeat until one list runs out.
- Copy whatever remains of the other list to the end of the output.
The leftover elements in step 4 need no comparisons. They are already sorted, and every one of them is at least as large as everything already in the output.
The Implementation
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
print(merge([3, 27, 38, 43], [9, 10, 82])) # [3, 9, 10, 27, 38, 43, 82]
print(merge([], [1, 2])) # [1, 2]
print(merge([5, 5], [5])) # [5, 5, 5]After the loop ends, at most one of the two extend calls adds anything. The loop only stops when i == len(left) or j == len(right), so one of the slices is empty. Calling both is simpler than checking which list ran out, and an empty extend costs almost nothing.
The comparison is <=, not <. On a tie it takes the element from left. This choice keeps equal elements in their original order, a property called stability, which has its own chapter later. For now, remember that <= is deliberate.
Tracing an Example
Merge left = [3, 27, 38, 43] with right = [9, 10, 82]:
| Step | left[i] | right[j] | Taken | Output so far |
|---|---|---|---|---|
| 1 | 3 | 9 | 3 (left) | [3] |
| 2 | 27 | 9 | 9 (right) | [3, 9] |
| 3 | 27 | 10 | 10 (right) | [3, 9, 10] |
| 4 | 27 | 82 | 27 (left) | [3, 9, 10, 27] |
| 5 | 38 | 82 | 38 (left) | [3, 9, 10, 27, 38] |
| 6 | 43 | 82 | 43 (left) | [3, 9, 10, 27, 38, 43] |
| end | — | 82 | rest of right | [3, 9, 10, 27, 38, 43, 82] |
There are six comparisons for seven elements. The last element, 82, was copied without a comparison because left had run out.
Why the Output Is Sorted
The loop maintains an invariant, a statement that is true before every iteration:
resultholds thei + jsmallest elements of the two inputs, in sorted order.- Every element in
resultis less than or equal toleft[i]andright[j], for whichever of those still exist.
At the start, result is empty, so the invariant holds trivially. On each iteration the algorithm appends min(left[i], right[j]). Every remaining element of left is at least left[i], and every remaining element of right is at least right[j], so this minimum is the smallest element not yet output. Appending it keeps result sorted and keeps the invariant true. When one list is exhausted, the other list's remainder is sorted and no smaller than anything in result, so appending it finishes a sorted output. The chapter on correctness reuses this argument as one step of an induction over the whole algorithm.
Why It Runs in Linear Time
Each loop iteration does a constant amount of work and moves exactly one element into result. No element is ever looked at again after it is output. The total work is therefore proportional to m + n, which is O(m + n).
The number of comparisons has tight bounds:
| Case | Comparisons | Example |
|---|---|---|
| Fewest | min(m, n) | every element of `left` is smaller than every element of `right` |
| Most | m + n − 1 | the inputs interleave until the very last element |
The upper bound is m + n − 1 because the loop runs at most once per output element, and when only one element remains, one list is already empty. You can check both bounds directly:
def merge_count(left, right):
result, comparisons = [], 0
i = j = 0
while i < len(left) and j < len(right):
comparisons += 1
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result, comparisons
print(merge_count([1, 2, 3], [4, 5, 6])) # ([1, 2, 3, 4, 5, 6], 3) -> min(m, n)
print(merge_count([1, 3, 5], [2, 4, 6])) # ([1, 2, 3, 4, 5, 6], 5) -> m + n - 1When merge sort merges two halves of a list of size n, this step costs Θ(n). That linear cost per level is the O(n) term in the recurrence T(n) = 2T(n/2) + O(n), which a later chapter solves.
Common Errors
Forgetting the leftovers
If you leave out the two extend lines, the function silently drops the tail of whichever list did not run out. merge([1, 2], [3, 4]) would return [1, 2]. Empty inputs and inputs where every element of one list is smaller than every element of the other are the cases that catch this.
Using `pop(0)` to consume the lists
A version that pops from the front looks tidy:
def merge_slow(left, right):
left, right = list(left), list(right)
result = []
while left and right:
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
return result + left + right
print(merge_slow([1, 4], [2, 3])) # [1, 2, 3, 4]The output is correct, but list.pop(0) shifts every remaining element down by one, which costs O(length). Across the whole merge, this makes the function O((m + n)²) in the worst case. Popping from the end, using collections.deque.popleft(), or using indices as shown earlier all avoid this.
Swapping `<=` for `<`
With <, ties go to right. The output is still sorted, so tests that only check sortedness will pass. The chapter on stability explains what breaks.
Merging unsorted inputs
The merge assumes both inputs are sorted. Given [5, 1] and [3], it returns [3, 5, 1] without raising an error. The algorithm does not check this precondition. Merge sort guarantees it by construction.
An Index-Based Merge for Arrays
The slicing version allocates a new list on every call. Array-based merge sorts usually merge two adjacent sorted ranges of one array, a[lo:mid] and a[mid:hi], back into the same array. They use a reusable auxiliary buffer for this. The bottom-up variant and the space analysis later in the tutorial use this form.
def merge_into(a, lo, mid, hi, aux):
"""Merge sorted a[lo:mid] and a[mid:hi] into a[lo:hi], using aux as scratch."""
aux[lo:hi] = a[lo:hi]
i, j = lo, mid
for k in range(lo, hi):
if i >= mid:
a[k] = aux[j]
j += 1
elif j >= hi:
a[k] = aux[i]
i += 1
elif aux[i] <= aux[j]:
a[k] = aux[i]
i += 1
else:
a[k] = aux[j]
j += 1
a = [1, 4, 7, 2, 3, 9]
aux = [None] * len(a)
merge_into(a, 0, 3, 6, aux)
print(a) # [1, 2, 3, 4, 7, 9]The function first copies the range into aux, then writes the merged output back into a. The order of the branch checks matters. Each list's exhaustion test (i >= mid, j >= hi) must come before the comparison, or the code will read past the end of a run. The copy is needed because writing directly into a[k] could overwrite elements of the left run before they are read.
Testing a Merge
A randomized check against Python's built-in sorted catches most mistakes, including dropped tails and off-by-one errors:
import random
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
for _ in range(10_000):
left = sorted(random.randint(0, 9) for _ in range(random.randint(0, 6)))
right = sorted(random.randint(0, 9) for _ in range(random.randint(0, 6)))
assert merge(left, right) == sorted(left + right), (left, right)
print("all merges correct")The small value range (0 to 9) produces many duplicates, and the length range includes zero, so the test covers ties and empty inputs.
Exercise
How many comparisons does merge perform on left = [2, 4, 6, 8] and right = [1, 3, 5, 7]? Is this the best case, the worst case, or neither?
Show answer
Seven. The outputs are 1, 2, 3, 4, 5, 6, 7, each after one comparison, and then 8 is copied with no comparison because right is exhausted. Seven equals m + n − 1 = 4 + 4 − 1, so this is the worst case.
Exercise
In merge_into, what goes wrong if you move the elif aux[i] <= aux[j] test to be the first branch, before the exhaustion checks?
Show answer
Once one run is exhausted, i equals mid or j equals hi. The comparison then reads aux[mid] (which belongs to the right run) or aux[hi] (outside the range, or past the end of the list). That gives a wrong result or an IndexError. The exhaustion checks must come first so the code never compares against an element that is not part of a live run.
Exercise
Write a function merge_k(lists) that merges k sorted lists by merging them pairwise, left to right. If every list has length n, what is its running time, and why is it worse than merging in balanced pairs?
Show answer
For example: result = []; for lst in lists: result = merge(result, lst); return result. The i-th merge costs about i·n, so the total is n(1 + 2 + ... + k) = O(n·k²). Merging in balanced pairs (pair up the lists, merge each pair, repeat) touches every element once per round across log k rounds, for O(n·k·log k).