A linear search (sequential search) checks each item in a list one by one from the beginning until the target is found or the end is reached.
found ← FALSE
index ← 1
WHILE index <= length AND found = FALSE DO
IF list[index] = target THEN
found ← TRUE
ELSE
index ← index + 1
ENDIF
ENDWHILE
IF found = TRUE THEN
OUTPUT "Found at position ", index
ELSE
OUTPUT "Not found"
ENDIF
Checks: 7 (no) → 15 (no) → 42 ✓ Found at position 3
| Advantages | Disadvantages |
|---|---|
| Works on unsorted data | Slow for large lists (checks every element) |
| Simple to implement and understand | Maximum comparisons = number of items (n) |
| Can be used on any data type | Not efficient |
A binary search is a much more efficient algorithm — but it requires the data to be sorted in order first. It works by repeatedly halving the search space.
low ← 1
high ← length
found ← FALSE
WHILE low <= high AND found = FALSE DO
mid ← (low + high) DIV 2
IF list[mid] = target THEN
found ← TRUE
ELSE IF list[mid] < target THEN
low ← mid + 1
ELSE
high ← mid - 1
ENDIF
ENDWHILE
IF found = TRUE THEN
OUTPUT "Found at position ", mid
ELSE
OUTPUT "Not found"
ENDIF
| Linear Search | Binary Search | |
|---|---|---|
| Data must be sorted? | No | Yes |
| Maximum comparisons (n=1000) | 1000 | ~10 (log₂ 1000) |
| Efficiency | Low (for large data) | High |
| Complexity | Simple | More complex |
| Works on linked lists? | Yes | Difficult |
5 questions · 10 marks
| Term | Definition |
|---|
10 minutes · mixed marks