CIE AS & A Level Computer Science, section 19.1 (Algorithms)
Linear search
Check each item in turn, from the start, until the item is found or the end of the list is reached. The list does not need to be sorted.
Found ← FALSE
Index ← 1
WHILE Index <= ListLength AND Found = FALSE
IF List[Index] = Target THEN
Found ← TRUE
ELSE
Index ← Index + 1
ENDIF
ENDWHILE
- Best case: the item is first (1 comparison).
- Worst case: the item is last or missing ( comparisons).
Binary search
The list must be sorted. Compare the target with the middle item, and discard half of the list each time.
- Set
lowto the first position andhighto the last. - Find the middle,
mid. - If the item at
midis the target, it is found. - If the target is smaller, set
hightomid - 1; if larger, setlowtomid + 1. - Repeat while
low <= high. Iflow > high, the item is not in the list.
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if target < items[mid]:
high = mid - 1
else:
low = mid + 1
return -1
data = [3, 8, 12, 19, 25, 31, 40]
print(binary_search(data, 25)) # 4
print(binary_search(data, 10)) # -1
Comparing
| Linear | Binary | |
|---|---|---|
| List must be sorted? | no | yes |
| Worst case comparisons | about | |
| 1 000 000 items | up to 1 000 000 | about 20 |
Binary search is far faster for a large sorted list, but linear is better for short or unsorted lists.
Common mistake: using binary search on an unsorted list: it will give wrong answers. Also, when the target is larger, search above mid (set low = mid + 1), and do not forget the + 1 and - 1, which prevent an endless loop.
Exam tip: in a trace, show low, high and mid at each step. State clearly why the item is not found: low has become greater than high.
Check yourself
What condition must be met to use a binary search?
The list must be sorted.
How many comparisons might a binary search of 1 000 items need at most?
About 10, because .
When is linear search the better choice?
When the list is short or unsorted.