AQA GCSE Computer Science (8525), section 3.1.4 (Sorting algorithms)
How it works
A merge sort uses divide and conquer. It has two stages.
- Divide: keep splitting the list in half until every part has just one item. A list of one item is already sorted.
- Merge: join the parts back together in pairs, always putting the items in order as they are merged.
Merging two sorted lists
To merge two sorted lists, compare the first item of each, take the smaller one into the new list, and repeat until one list is empty. Then add the remaining items of the other list.
Merging [3, 8] and [1, 9]:
| Compare | Take | New list |
|---|---|---|
| 3 and 1 | 1 | 1 |
| 3 and 9 | 3 | 1, 3 |
| 8 and 9 | 8 | 1, 3, 8 |
| (first list empty) | 9 | 1, 3, 8, 9 |
Worked example
Sort 6, 2, 9, 4, 1, 7, 3.
Python
def merge_sort(data):
if len(data) <= 1:
return data
middle = len(data) // 2
left = merge_sort(data[:middle])
right = merge_sort(data[middle:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
print(merge_sort([6, 2, 9, 4, 1, 7, 3])) # [1, 2, 3, 4, 6, 7, 9]
You do not need to write this code in the exam, but you must understand how the algorithm works.
Merge sort and bubble sort compared
| Bubble sort | Merge sort | |
|---|---|---|
| Method | swaps neighbouring items repeatedly | splits the list, then merges sorted parts |
| Speed on large lists | slow | much faster |
| Memory | little (sorts in place) | needs extra memory for the new lists |
| Complexity | simple | harder to understand and write |
| Best for | short lists, or lists that are almost sorted | long lists |
Common mistake: stopping the divide stage too early (leaving parts with 2 or more items), or merging by just joining the two lists together. Each merge must compare items so the result is in order.
Exam tip: show the divide stage first (down to single items) and then the merge stage in order. When comparing the sorts, give a point for each algorithm: for example, "merge sort is faster on long lists but uses more memory".
Check yourself
What do you do in the divide stage of a merge sort?
Keep splitting the list in half until every part contains one item.
Merge the sorted lists 2, 5 and 1, 6.
1, 2, 5, 6.
Give one advantage of merge sort over bubble sort.
It is much faster on large lists.