Sub topic 1
The Divide-and-Conquer Idea
Prerequisites
This chapter assumes you can read basic Python, work with lists and indexing, follow a recursive function through the call stack, and understand Big-O notation.
Divide, Conquer, Combine
Divide and conquer solves a problem in three steps:
- Divide the input into smaller subproblems.
- Conquer each subproblem recursively.
- Combine the sub-results into the full answer.
Merge sort splits a list into two halves, sorts each half, and combines the halves by merging them. Splitting takes almost no work. The merge does most of it.
Merging Two Sorted Lists in Linear Time
Two sorted lists can be merged with one pointer per list. At each step, compare the two front elements and append the smaller one. When one list runs out, append whatever is left of the other. Every comparison places one element, so merging lists of total length n takes O(n) time.
A common mistake is to finish the loop and forget the leftover elements. The two extend calls below handle them.
Splitting Until One Element Remains
The recursion needs a base case. A list with zero or one element is already sorted, so the function returns a copy of it. Any longer list is split at mid = len(items) // 2. Each split halves the length, so the recursion goes about log₂ n levels deep.
Putting It Together: Recursive Merge Sort
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
def merge_sort(items):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge(merge_sort(items[:mid]), merge_sort(items[mid:]))
print(merge_sort([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]Exercise
What goes wrong if the base case is changed to if len(items) == 0:?
Show answer
A one-element list then gets split into an empty list and a one-element list. The one-element list recurses on itself forever, so Python raises a RecursionError.
Exercise
How many comparisons does merge([1, 2, 3], [4, 5, 6]) make?
Show answer
Three. Each element of the left list is compared with 4 and appended. The left list then runs out, and [4, 5, 6] is added by extend without any more comparisons.