Edexcel International Advanced Level Computer Science, point 15.2.1
Definition
Merge sort is a divide-and-conquer sorting algorithm (15.1.1). It splits the list into halves until each part has one item (a list of one item is already sorted), then merges pairs of sorted parts back together to form larger sorted lists, until one sorted list remains.
Function
It sorts a list in time in every case, which is far faster than bubble or insertion sort () for large lists.
Characteristics
- Divide and conquer, usually recursive (Unit 4: 21.1.1).
- Always splits in the middle, so the work is the same whatever the order of the data.
- Needs extra memory () for merging.
- Stable: equal items keep their original order.
Operation
Divide
Split the list into two halves, then split each half, and so on, until every part has a single item.
Conquer (merge)
Merge two sorted lists into one sorted list: compare the front items of each list, take the smaller, and repeat until one list is empty, then add what is left of the other.
Merge [3, 27] and [10, 43]:
compare 3 and 10 -> take 3 result: [3]
compare 27 and 10 -> take 10 result: [3, 10]
compare 27 and 43 -> take 27 result: [3, 10, 27]
first list empty -> add 43 result: [3, 10, 27, 43]
Hand trace: sort [38, 27, 43, 3, 9, 82, 10]
Divide:
Merge (working back up):
[38] + [27] -> [27, 38] [43] + [3] -> [3, 43]
[9] + [82] -> [9, 82] [9, 82] + [10] -> [9, 10, 82]
[27, 38] + [3, 43] -> [3, 27, 38, 43]
[3, 27, 38, 43] + [9, 10, 82] -> [3, 9, 10, 27, 38, 43, 82]
Result: [3, 9, 10, 27, 38, 43, 82].
Code
def merge_sort(items):
if len(items) <= 1: # base case: already sorted
return items
mid = len(items) // 2
left = merge_sort(items[:mid]) # divide
right = merge_sort(items[mid:])
return merge(left, right) # combine
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps equal items in order
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:]) # add any remaining items
result.extend(right[j:])
return result
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
Efficiency
- There are levels of splitting.
- At each level, merging does about comparisons in total.
- Time: in the best, average and worst cases.
- Space: for the extra lists (and for the recursion).
| Merge sort | Bubble sort | |
|---|---|---|
| 1 000 | about 10 000 | 1 000 000 |
| 1 000 000 | about 20 000 000 |
Benefits
- Fast and predictable: always, no bad case.
- Stable.
- Works well on large data sets and on linked lists and data on disk (external sorting).
- Suits parallel processing: the two halves are independent (11.1.4).
Drawbacks
- Needs extra memory (), unlike in-place sorts.
- More complex than bubble or insertion sort.
- Recursion overhead, so slower than a simple sort on very small lists.
- Does the full amount of work even when the list is already sorted.
Worked example
Task: hand trace a merge sort on [6, 2, 8, 4], and count the comparisons made in the merges.
Divide: [6, 2, 8, 4] into [6, 2] and [8, 4], then into [6], [2], [8], [4].
Merge:
| Merge | Comparisons | Result |
|---|---|---|
[6] and [2] |
6 vs 2: take 2; then add 6 (1 comparison) | [2, 6] |
[8] and [4] |
8 vs 4: take 4; then add 8 (1 comparison) | [4, 8] |
[2, 6] and [4, 8] |
2 vs 4: take 2. 6 vs 4: take 4. 6 vs 8: take 6. Add 8 (3 comparisons) | [2, 4, 6, 8] |
Total: 5 comparisons. A bubble sort of the same list would make up to 6, but the gap grows enormously for larger lists.
Exam tip: show the splitting (down to single items) and then each merge, in order. When merging, compare front items and take the smaller. State and the extra memory needed. In Unit 4, write the recursive version.
Check yourself
What is the base case of merge sort?
A list of one item (or none), which is already sorted.
What is the time complexity of merge sort?
O(n log n) in the best, average and worst cases.
Merge [2, 9] and [4, 5]
[2, 4, 5, 9].
Give one advantage and one disadvantage of merge sort
Advantage: predictable O(n log n) speed with no bad case. Disadvantage: needs extra memory for merging.
Why is merge sort a divide-and-conquer algorithm?
It divides the list into halves, sorts each half (recursively), and combines the sorted halves by merging.