Sub topic 2
Merging Two Sorted Lists in Linear Time
This chapter assumes you can write loops in Python, index into lists, and read Big-O notation. It covers the merge step only. Splitting and recursion come in later chapters.
The Problem the Merge Solves
You have two lists, and each one is already sorted. You want a single sorted list that holds every element from both. Merge sort's whole speed advantage depends on doing this in time proportional to the total number of elements, written O(n), where n is the combined length.
The key fact is that the smallest remaining element overall must be at the front of one of the two lists. You never need to look deeper than the two front elements.
The Two-Pointer Method
Keep one index into each list. At each step, compare the two elements the indices point to. Append the smaller one to the result and advance that list's index. When one list runs out, the rest of the other list is already sorted and larger than everything taken so far, so you copy it over unchanged.
The Code
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]After the loop ends, at most one of the two extend calls adds anything. Calling both is simpler than checking which list has elements left.
A Worked Trace
Merging [3, 27, 38, 43] with [9, 10, 82]:
| Step | left[i] | right[j] | Taken | Result so far |
|---|---|---|---|---|
| 1 | 3 | 9 | 3 | [3] |
| 2 | 27 | 9 | 9 | [3, 9] |
| 3 | 27 | 10 | 10 | [3, 9, 10] |
| 4 | 27 | 82 | 27 | [3, 9, 10, 27] |
| 5 | 38 | 82 | 38 | [3, 9, 10, 27, 38] |
| 6 | 43 | 82 | 43 | [3, 9, 10, 27, 38, 43] |
| end | (empty) | 82 | 82 | [3, 9, 10, 27, 38, 43, 82] |
Why It Runs in Linear Time
Each loop iteration does one comparison and moves exactly one element into result. No element is ever moved twice. With lengths a and b, the loop runs at most a + b - 1 times, and the final copy handles whatever is left. Total work is O(a + b). The result list also takes O(a + b) extra space, which a later chapter discusses.
The worst case for comparisons happens when the two lists interleave all the way to the end. The best case is when every element of one list is smaller than every element of the other. Then the loop runs only min(a, b) times before one side is exhausted.
Common Errors
- Dropping the leftovers. If you forget the
extendcalls after the loop, the tail of the longer list is silently lost. - Using
orin the loop condition.while i < len(left) or j < len(right)will index past the end of the list that ran out first and raiseIndexError. - Using
<instead of<=. The output is still sorted, but equal elements from the right list jump ahead of equal elements from the left. The chapter on stability explains why this matters. - Feeding unsorted input. The merge assumes both inputs are sorted. If either one is not, the output is wrong and no error is raised.
Exercise
What is the maximum number of comparisons merge performs on two sorted lists of lengths 4 and 3, and what input pair produces it?
Show answer
At most 4 + 3 - 1 = 6 comparisons. This happens when the lists interleave so that neither runs out until the last element, for example [1, 3, 5, 7] and [2, 4, 6]. After six comparisons the right list is empty, and 7 is copied over without a comparison.
Exercise
Rewrite the loop condition as while i < len(left) or j < len(right) and run merge([1, 2], [5]). What happens and why?
Show answer
It raises IndexError. Once 1 and 2 are taken, i equals 2 but the loop keeps going because j < 1. The comparison left[2] <= right[0] then indexes past the end of left.