Prerequisite · Apply · Trace · Efficiency
low = 0, high = LEN-1 — initialise the search boundaries to the full list.WHILE low <= high AND found==FALSE — loop continues while there is still a valid range to search and the target hasn't been found.mid = (low+high) DIV 2 — integer division gives the middle index of the current range.data[mid] < target → low = mid+1 — target is in the right half, discard the left.ELSE → high = mid-1 — target is in the left half, discard the right.found==FALSE, the WHILE condition became low>high — the search space is empty. Target is not present.low <= high is now FALSE — loop exits.| low | high | mid | data[mid] | comparison | update | OUTPUT |
|---|---|---|---|---|---|---|
| 0 | 9 | 4 | 14 | 35>14 | low=5 | |
| 5 | 7 | 29 | 35>29 | low=8 | ||
| 8 | 8 | 35 | 35==35 ✓ | found=TRUE | 8 |
| low | high | mid | data[mid] | comparison | update |
|---|---|---|---|---|---|
| 0 | 9 | 4 | 14 | 20>14 | low=5 |
| 5 | 7 | 29 | 20<29 | high=6 | |
| 6 | 5 | 18 | 20>18 | low=6 | |
| 6 | 6 | 23 | 20<23 | high=5 | |
| low=6, high=5 → low>high → EXIT LOOP → output "Not found" | |||||
| LINEAR SEARCH | BINARY SEARCH | |
|---|---|---|
| Sorted data needed? | No | YES — required |
| Best case | 1 | 1 |
| Worst case | n | log₂(n) |
| 1,000 items | up to 1,000 | up to 10 |
| 1,000,000 items | up to 1,000,000 | up to 20 |
(low + high) DIV 2 or equivalent. This is unique to binary search — linear search has no midpoint.low <= high.(lo+hi) DIV 2, the three-way IF/ELSE IF/ELSE comparison, and the pointer update (lo=centre+1 or hi=centre-1) (1 mark)Next up: 2.1.3c — Bubble Sort