Searching algorithms
Linear search
A linear search checks each item in turn, from the beginning, until it finds the target or reaches the end. It works on sorted or unsorted data. With six items it may need to check all six.
The animation checks for 6 in 7, 3, 9, 2, 6, 4 and highlights each item as it is compared.
Start with 7, 3, 9, 2, 6, 4.
Assume numbers contains six items and target is the value being searched for. The ERL and Python versions return the first matching index, or -1 if it is not present:
position = -1
FOR i = 0 TO 5
IF numbers[i] == target AND position == -1 THEN
position = i
ENDIF
NEXT i
Key terms
Binary search
A binary search repeatedly checks the middle item and discards the half that cannot contain the target. It is quicker than checking every item on a long list, but the data must already be sorted.
The animation searches for 7 in 2, 4, 6, 7, 9, 12. Each step compares the middle value and keeps only the possible half.
Start with 2, 4, 6, 7, 9, 12.
The following ERL and Python algorithms return the target's index, or -1 if it is absent. numbers is the same sorted list in both:
low = 0
high = 5
position = -1
WHILE low <= high
middle = (low + high) DIV 2
IF numbers[middle] == target THEN
position = middle
high = low - 1
ELSE IF numbers[middle] < target THEN
low = middle + 1
ELSE
high = middle - 1
ENDIF
ENDWHILE
Common mistake
Binary search can give the wrong result on unsorted data because discarding a half may discard the target.
Key terms
Comparing the two searches
| Linear search | Binary search | |
|---|---|---|
| Does the data need to be sorted? | No | Yes |
| Most checks for 1,000 items | 1,000 | 10 |
| On a short list | Fast enough, and simpler | Little faster |
| Code | Short and simple | Longer |
Binary search halves the items left to search at every check, so even a very long sorted list needs only a few checks. Linear search is the only choice when the data isn't sorted, unless it is sorted first, which takes time of its own.
Exam tip
To choose a search, look first at whether the data is sorted. If it is, and the list is long, binary search is usually the better choice.