Edexcel International Advanced Level Computer Science, point 21.1.1
The idea of merge sort is in 15.2.1. In Unit 4 you must implement and use a recursive merge sort, and be able to amend it. It divides the list in half, sorts each half recursively, and merges the two sorted halves.
The structure
merge_sort(list)
base case: fewer than 2 items -> already sorted, return it
divide: split into left half and right half
conquer: left = merge_sort(left half)
right = merge_sort(right half)
combine: return merge(left, right)
Implementation
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
# <= keeps equal items in order
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
# one side may have items left
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort(items):
if len(items) <= 1: # base case
return items
middle = len(items) // 2
left = merge_sort(items[:middle]) # recursive calls
right = merge_sort(items[middle:])
return merge(left, right) # combine
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
# [3, 9, 10, 27, 38, 43, 82]
Points to notice:
mergeis a separate subprogram (decomposition), and can be tested alone.- The loop ends when one side is used up, then
extendadds what's left of the other (already sorted). <=makes the sort stable (equal items keep their original order).merge_sortreturns a new list: the original isn't changed.- Each recursive call is on a smaller list, moving towards the base case.
Tracing the recursion
For [6, 2, 8, 4]:
merge_sort([6, 2, 8, 4])
merge_sort([6, 2])
merge_sort([6]) -> [6]
merge_sort([2]) -> [2]
merge([6], [2]) -> [2, 6]
merge_sort([8, 4])
merge_sort([8]) -> [8]
merge_sort([4]) -> [4]
merge([8], [4]) -> [4, 8]
merge([2, 6], [4, 8]) -> [2, 4, 6, 8]
merge([2, 6], [4, 8]) step by step:
i |
j |
Compare | Take | result |
|---|---|---|---|---|
| 0 | 0 | 2 vs 4 | 2 | [2] |
| 1 | 0 | 6 vs 4 | 4 | [2, 4] |
| 1 | 1 | 6 vs 8 | 6 | [2, 4, 6] |
| 2 | 1 | left used up | add [8] |
[2, 4, 6, 8] |
Amending the algorithm
Descending order
Change one comparison in merge (<= to >=):
def merge_desc(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] >= right[j]: # the only change
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]
A key function (sorting records)
Add a key parameter so any field can be used:
def merge_sort_by(items, key=lambda x: x):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort_by(items[:mid], key)
right = merge_sort_by(items[mid:], key)
result, i, j = [], 0, 0
while i < len(left) and j < len(right):
if key(left[i]) <= key(right[j]):
result.append(left[i]); i += 1
else:
result.append(right[j]); j += 1
return result + left[i:] + right[j:]
students = [("Amy", 72), ("Raj", 91), ("Sam", 58)]
print(merge_sort_by(students, key=lambda s: s[1]))
# [('Sam', 58), ('Amy', 72), ('Raj', 91)]
Counting comparisons
comparisons = 0
def merge_counted(left, right):
global comparisons
result, i, j = [], 0, 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
return result + left[i:] + right[j:]
For [6, 2, 8, 4] the merges make 1 + 1 + 3 = 5 comparisons; for items, about .
Efficiency
- Time: in every case ( levels of splitting, about work in each).
- Space: (the new lists).
- Slicing (
items[:mid]) copies items, so an index-based version (passinglowandhigh) uses less memory, but is harder to write.
Test plan
| Test | Data | Expected |
|---|---|---|
| Empty list | [] |
[] |
| One item | [5] |
[5] |
| Already sorted | [1, 2, 3] |
[1, 2, 3] |
| Reverse order | [3, 2, 1] |
[1, 2, 3] |
| Duplicates | [2, 1, 2, 1] |
[1, 1, 2, 2] |
| Negatives | [3, -1, 0] |
[-1, 0, 3] |
| Odd and even lengths | 5 items and 6 items | both sorted |
| Original unchanged | Check the input list afterwards | The same as before |
tests = [[], [5], [1, 2, 3], [3, 2, 1], [2, 1, 2, 1], [3, -1, 0],
[5, 3, 8, 1, 9], [6, 5, 4, 3, 2, 1]]
for t in tests:
original = t[:]
assert merge_sort(t) == sorted(t)
assert t == original # the input is unchanged
print("All merge sort tests passed")
Worked example
Task: sort the list ["pear", "apple", "fig", "kiwi"] alphabetically, then by length, using the code above.
words = ["pear", "apple", "fig", "kiwi"]
# ['apple', 'fig', 'kiwi', 'pear']
print(merge_sort(words))
# ['fig', 'pear', 'kiwi', 'apple']
print(merge_sort_by(words, key=len))
Alphabetical: strings compare character by character, so apple < fig < kiwi < pear. By length (4, 5, 3, 4): fig (3), then pear and kiwi (both 4), which stay in their original order (pear before kiwi) because the sort is stable, then apple (5).
Exam tip: write merge first, then merge_sort. Don't forget the base case (len <= 1) or the leftover items after the loop. Use <= for stability. State the time () and the extra memory. Test with empty, one-item, duplicate and reversed lists.
Check yourself
What is the base case of merge sort?
A list of zero or one item, which is already sorted.
What does the merge subprogram do?
It combines two sorted lists into one sorted list by repeatedly taking the smaller of the two front items.
What change makes merge sort sort in descending order?
Change the comparison in merge from <= to >=.
Why does the merge loop need extend after it?
When one list is used up, the remaining items in the other are already sorted and larger, so they are added to the end.