AQA GCSE Computer Science (8525), section 3.1.3 (Searching algorithms)
How it works
A linear search looks at each item in turn, starting at the beginning of the list, until it either finds the item or reaches the end of the list.
The list does not need to be sorted.
Steps
- Start at the first item.
- Compare the item with the one you are looking for.
- If they match, stop: found.
- Otherwise move to the next item.
- If you reach the end without a match, the item is not in the list.
Pseudo-code
names ← ["Ali", "Bea", "Cara", "Dev", "Eve"]
target ← USERINPUT
found ← False
i ← 0
WHILE i < LEN(names) AND found = False
IF names[i] = target THEN
found ← True
ELSE
i ← i + 1
ENDIF
ENDWHILE
IF found THEN
OUTPUT "Found at position " + i
ELSE
OUTPUT "Not found"
ENDIF
Python
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1 # not found
names = ["Ali", "Bea", "Cara", "Dev", "Eve"]
print(linear_search(names, "Dev")) # 3
print(linear_search(names, "Zoe")) # -1
Example
Searching for 14 in [9, 3, 14, 7, 20]:
| Step | Item checked | Match? |
|---|---|---|
| 1 | 9 | no |
| 2 | 3 | no |
| 3 | 14 | yes, found |
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Simple to write and understand | Slow for long lists, as every item may need checking |
| Works on unsorted data | |
| Works on any type of list |
Best case: the item is the first one. Worst case: the item is the last, or is not in the list at all, so every item is checked.
Common mistake: stopping the search after checking just the first item and finding no match. The search can only say the item is not there after every item has been checked. Also, remember to check you do not run past the end of the list.
Exam tip: for a linear search, say it checks the items one at a time in order from the start. State that the list does not need to be sorted, and show the checks in a table if asked to trace it.
Check yourself
Does the list need to be sorted for a linear search?
No.
How many items are checked in the worst case when searching a list of 50 items?
All 50.
Give one disadvantage of a linear search.
It is slow for long lists, because many items may have to be checked.