CIE AS & A Level Computer Science, section 19.1 (Algorithms)
Bubble sort
Repeatedly compare neighbouring items and swap them if they are in the wrong order. After each pass, the largest unsorted item has moved to the end ("bubbled up").
Sorting [5, 3, 8, 1]:
| Pass | List after |
|---|---|
| 1 | 3, 5, 1, 8 |
| 2 | 3, 1, 5, 8 |
| 3 | 1, 3, 5, 8 |
Improved bubble sort
- Stop if a pass makes no swaps (the list is sorted).
- Each pass can ignore the items already in place at the end.
def bubble_sort(items):
n = len(items)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
n -= 1 # the last item is now in place
return items
print(bubble_sort([5, 3, 8, 1])) # [1, 3, 5, 8]
Insertion sort
Treat the start of the list as sorted. Take the next item and insert it into its correct place in the sorted part, shifting larger items right.
Sorting [5, 3, 8, 1]:
| Step | Sorted part | Item inserted | Result |
|---|---|---|---|
| 1 | 5 | 3 | 3, 5, 8, 1 |
| 2 | 3, 5 | 8 | 3, 5, 8, 1 |
| 3 | 3, 5, 8 | 1 | 1, 3, 5, 8 |
def insertion_sort(items):
for i in range(1, len(items)):
value = items[i]
j = i - 1
while j >= 0 and items[j] > value:
items[j + 1] = items[j] # shift right
j -= 1
items[j + 1] = value
return items
print(insertion_sort([5, 3, 8, 1])) # [1, 3, 5, 8]
Comparing
| Bubble sort | Insertion sort | |
|---|---|---|
| Worst case | ||
| Already sorted | quick with the no-swap check, | |
| Extra memory | none | none |
| Good for | small lists | small or nearly sorted lists |
Insertion sort usually does fewer operations than bubble sort.
Common mistake: stopping bubble sort after one pass. The sort is only complete when a pass makes no swaps. Also, in insertion sort the item is inserted into the sorted part, not swapped with its neighbour repeatedly from the end of the list.
Exam tip: for a trace, show the list after each pass (bubble) or each insertion (insertion sort). Mention the swap flag if asked how to improve bubble sort.
Check yourself
What is the position of the largest item after the first pass of a bubble sort?
At the end of the list.
How can bubble sort be made more efficient for a nearly sorted list?
Stop as soon as a pass makes no swaps.
Which sort builds a sorted section at the start and inserts the next item into it?
Insertion sort.