SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Cambridge IGCSE 0478 · Topic 7 · 7.3b

Linear &
Binary Search

How Each Works · Pseudocode · Comparison · When to Use Each

CSZoneCambridge IGCSE Computer Science 0478
Linear Search

Check Each Item in Turn

Linear search: starts at the first item and checks each one in order until the target is found or all items have been checked. Works on unsorted lists.
found ← FALSE
i ← 1
WHILE i <= n AND found = FALSE DO
IF data[i] = target
THEN found ← TRUE
ELSE i ← i + 1
ENDIF
ENDWHILE
IF found THEN OUTPUT i ELSE OUTPUT "Not found"
Binary Search

Halve the Search Space Each Time

Binary search: only works on a sorted list. Finds the middle item; if target is less, search the left half; if greater, search the right half. Repeat until found or list exhausted.
low ← 1 high ← n
found ← FALSE
WHILE low <= high AND found = FALSE DO
mid ← (low + high) DIV 2
IF data[mid] = target THEN found ← TRUE
ELSE IF target < data[mid] THEN high ← mid - 1
ELSE low ← mid + 1
ENDIF
ENDWHILE
Comparison: Linear vs Binary

Which is Better and When?

FeatureLinear SearchBinary Search
List must be sorted?NoYes
Speed (worst case)Slow (checks all n)Fast (log₂ n checks)
Works for small lists?YesYes
Best for large lists?NoYes
Example: binary search on 1000 items needs at most ~10 checks; linear search needs up to 1000
Exam Practice

Have a go at this question

Cambridge IGCSE 0478 style
A sorted list contains [2, 5, 8, 12, 17, 23, 30]. Trace a binary search for the value 17, showing the value of low, high and mid at each step.
4 marks
Step 1: low=1, high=7, mid=4 → data[4]=12 < 17 → low=5 [1]
Step 2: low=5, high=7, mid=6 → data[6]=23 > 17 → high=5 [1]
Step 3: low=5, high=5, mid=5 → data[5]=17 = target → found! [1]
Total comparisons: 3 [1]
Key Takeaways

What to Remember

Linear search: checks each item one by one; works on unsorted lists; slow for large lists
Binary search: halves the search space each time; REQUIRES sorted list; much faster
Binary search: mid = (low + high) DIV 2; compare, then move low or high accordingly
For unsorted/small lists → linear; for large sorted lists → binary is significantly more efficient