CAIE 9618 · Paper 2 · Topic 2.1.3
Searching
Algorithms
Linear Search · Binary Search · Trace Tables · Efficiency Comparison
CSZone
Cambridge International AS & A Level Computer Science 9618
Linear Search
Check Every Element in Order
A linear search sequentially checks each element of a list until the target is found or the end is reached. Works on unsorted or sorted data.
DECLARE found : BOOLEAN
DECLARE i : INTEGER
found <- FALSE
i <- 1
WHILE i <= n AND NOT found DO
IF list[i] = target THEN
found <- TRUE
ELSE
i <- i + 1
ENDIF
ENDWHILE
IF found THEN OUTPUT i ELSE OUTPUT "-1" ENDIF
COMPLEXITY
Best case: O(1) — target is first element
Average: O(n/2) ≈ O(n)
Worst case: O(n) — target at end or not found
WHEN TO USE
List is unsorted. List is small. Items may not exist. Simplest to implement. Works on linked lists (no random access needed).
Binary Search
Divide and Conquer
Binary search works on sorted arrays only. It repeatedly halves the search space by comparing the target to the middle element.
lo <- 1, hi <- n, found <- FALSE
WHILE lo <= hi AND NOT found DO
mid <- (lo + hi) DIV 2
IF list[mid] = target THEN
found <- TRUE
ELSE IF target < list[mid] THEN
hi <- mid - 1
ELSE
lo <- mid + 1
ENDIF
ENDWHILE
COMPLEXITY
Best case: O(1) — target is the middle
Worst case: O(log₂ n)
1024 elements → max 10 comparisons!
REQUIREMENT
Must be sorted first. Requires random access (arrays, not linked lists). More complex to implement but vastly more efficient for large datasets.
Binary Search Trace
Worked Example: Find 42
Array: [5, 12, 18, 25, 30, 42, 56, 70, 88, 99] — sorted, n=10, target=42
| lo | hi | mid | list[mid] | Action |
| 1 | 10 | 5 | 30 | 30 < 42 → lo = mid+1 = 6 |
| 6 | 10 | 8 | 70 | 70 > 42 → hi = mid-1 = 7 |
| 6 | 7 | 6 | 42 | Found! Return index 6 |
Only 3 comparisons needed to find 42 in a 10-element array. Linear search would need up to 6 comparisons for this item.