At a glance
| Algorithm | What it does | Needs a sorted list? | Speed on a long list |
|---|---|---|---|
| Linear search | Checks every item in order | No | Slow |
| Binary search | Halves the list each step | Yes | Fast |
| Bubble sort | Swaps neighbouring pairs | – | Slow |
| Insertion sort | Inserts each item into a sorted part | – | Slow, but good on nearly sorted lists |
| Merge sort | Splits, then merges in order | – | Fast |
You do not need Big O notation at GCSE. Compare algorithms in words: how many comparisons they make and whether the list must be sorted.
Linear search
- Start at the first item.
- If it matches the target, stop: found.
- Otherwise move to the next item.
- If you reach the end, the target is not in the list.
found ← False
i ← 0
WHILE i < LEN(items) AND found = False
IF items[i] = target THEN
found ← True
ENDIF
i ← i + 1
ENDWHILE
Binary search
Binary search only works on a sorted list. It checks the middle item, then throws away the half that cannot contain the target.
low ← 0
high ← LEN(items) - 1
found ← False
WHILE low ≤ high AND found = False
mid ← (low + high) DIV 2
IF items[mid] = target THEN
found ← True
ELSE IF items[mid] < target THEN
low ← mid + 1
ELSE
high ← mid - 1
ENDIF
ENDWHILE
Bubble sort
- Compare the first two items. If they are in the wrong order, swap them.
- Move along one place and repeat to the end of the list. That is one pass.
- After each pass the largest unsorted item is in its final place.
- Repeat passes until a full pass makes no swaps.
Worked trace: [5, 3, 8, 1]
| Pass | List after the pass | Swaps |
|---|---|---|
| 1 | [3, 5, 1, 8] | 2 |
| 2 | [3, 1, 5, 8] | 1 |
| 3 | [1, 3, 5, 8] | 1 |
| 4 | [1, 3, 5, 8] | 0, so stop |
Insertion sort
- Treat the first item as a sorted list of one.
- Take the next item and move it left past every larger item.
- Insert it in the gap. The sorted part is now one item longer.
- Repeat until every item has been inserted.
Trace on [5, 3, 8, 1]: [3, 5, 8, 1] → [3, 5, 8, 1] → [1, 3, 5, 8].
Merge sort
- Divide: split the list in half again and again until every list has one item.
- Merge: merge pairs of lists, comparing the front items and taking the smaller each time.
- Keep merging until one sorted list remains.
Trace on [6, 2, 7, 3]: [6, 2] [7, 3] → [6] [2] [7] [3] → [2, 6] [3, 7] → [2, 3, 6, 7].
Exam checklist
- Can you trace each algorithm on a list of four to eight items?
- Can you say which algorithm a piece of pseudocode is?
- Can you explain why binary search needs a sorted list?
- Can you give one advantage and one disadvantage of each sort?
