Learning objectives:
- Know how linear search, binary search, bubble sort, insertion sort and merge sort work (2.11.1–2.11.2)
- Know their benefits and drawbacks (2.11.3)
- Compare algorithms by memory, execution time and comparisons (2.11.4)
- Know best, worst and average cases (2.11.5)
- Choose a suitable algorithm (2.11.6–2.11.7)
Searching
Linear search
Check each item in turn from the start until the target is found or the list ends.
- Works on unsorted data and is simple to write.
- Slow on large lists.
- Best case: target is first. Worst case: target is last or not there. Average: about half the list is checked.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
Binary search
Only works on sorted data. Check the middle item; if it is not the target, discard the half that cannot contain it and repeat on the other half.
- Much faster on large sorted lists, as each comparison halves the data.
- The data must be sorted first, and it is more complex to write.
- Best case: target is the first middle item. Worst case: the search keeps halving until one item is left.
Sorting
Bubble sort
Compare each pair of neighbouring items and swap them if they are in the wrong order. Repeat passes until a pass makes no swaps.
- Simple, sorts in place (little extra memory).
- Very slow on large lists. Best case: already sorted (one pass, no swaps).
Insertion sort
Take each item in turn and insert it into the correct place among the items already sorted to its left.
- Simple, in place, and fast on small or nearly sorted lists.
- Slow on large unsorted lists. Best case: already sorted. Worst case: sorted in reverse.
Merge sort
Split the list in half again and again until each part has one item, then merge the parts back together in order.
- Fast on large lists and the time taken is similar whatever the order of the data.
- More complex, and needs extra memory to hold the merged lists.
# Trace a bubble sort pass on [5, 2, 4, 1]
# compare 5,2 -> swap -> [2, 5, 4, 1]
# compare 5,4 -> swap -> [2, 4, 5, 1]
# compare 5,1 -> swap -> [2, 4, 1, 5] (largest is now at the end)
Comparing algorithms
- Memory space: how much extra storage it needs (merge sort needs the most here).
- Execution time: how long it takes as the data grows.
- Number of comparisons: how many times items are compared; fewer usually means faster.
Big O notation is not required. Explain cases using logical reasoning instead.
Choosing an algorithm
| Situation | Good choice | Why |
|---|---|---|
| Small or unsorted list, search once | Linear search | No need to sort first |
| Large sorted list, many searches | Binary search | Halves the data each step |
| Small or nearly sorted list | Insertion sort | Few moves needed, little memory |
| Large list, speed matters | Merge sort | Fast whatever the order, if memory allows |
| Teaching or tiny lists | Bubble sort | Easiest to understand |