Edexcel International Advanced Level Computer Science, point 10.3.2
This is the coding side of the binary search in 5.2.2. In Unit 2 you may need to amend and write it, in iterative or recursive form. The list must be sorted.
a. Iterative
def binary_search(items, target):
low = 0
high = len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif target < items[mid]:
high = mid - 1
else:
low = mid + 1
return -1
Key points:
lowandhighare indices of the part still being searched.mid = (low + high) // 2uses integer division.- The loop condition is
low <= high: whenlow > high, nothing is left, so the target isn't there. high = mid - 1andlow = mid + 1: the middle has already been checked, so it is excluded. Usingmidinstead causes an infinite loop.- Returns the index, or -1 if not found.
Counting the comparisons
def binary_search_count(items, target):
low, high, count = 0, len(items) - 1, 0
while low <= high:
mid = (low + high) // 2
count += 1
if items[mid] == target:
return mid, count
elif target < items[mid]:
high = mid - 1
else:
low = mid + 1
return -1, count
data = list(range(0, 200, 2)) # 100 sorted even numbers
print(binary_search_count(data, 98)) # found: few comparisons
print(binary_search_count(data, 99)) # not found: at most 7
For 100 items, at most 7 comparisons are needed ().
b. Recursive
The function calls itself on the half still to be searched.
def binary_search_rec(items, target, low, high):
if low > high: # base case: not found
return -1
mid = (low + high) // 2
if items[mid] == target: # base case: found
return mid
if target < items[mid]:
return binary_search_rec(items, target, low, mid - 1)
return binary_search_rec(items, target, mid + 1, high)
data = [4, 8, 15, 23, 42, 57, 61]
print(binary_search_rec(data, 57, 0, len(data) - 1)) # 5
print(binary_search_rec(data, 10, 0, len(data) - 1)) # -1
- Two base cases: not found (
low > high) and found. - Each call has a smaller range, which moves towards the base case.
- A wrapper can hide the extra parameters:
def search(items, target):
return binary_search_rec(items, target, 0, len(items) - 1)
Iterative and recursive compared
| Iterative | Recursive | |
|---|---|---|
| Structure | while loop |
Calls itself |
| Memory | Constant | A stack frame per call (about deep) |
| Clarity | Simple to trace | Matches the "halve it" idea closely |
| Risk | Infinite loop if bounds are wrong | Stack overflow if no base case |
| Speed | Slightly faster | Slightly slower |
Testing
Test with boundary and unusual cases:
| Test | Data | Expected |
|---|---|---|
| Item in the middle | [1, 3, 5, 7, 9], 5 |
2 |
| First item | 1 | 0 |
| Last item | 9 | 4 |
| Not present, inside the range | 4 | -1 |
| Smaller than all | 0 | -1 |
| Larger than all | 10 | -1 |
| One item | [5], 5 |
0 |
| Empty list | [], 5 |
-1 |
data = [1, 3, 5, 7, 9]
cases = [(5, 2), (1, 0), (9, 4), (4, -1), (0, -1), (10, -1)]
for target, expected in cases:
assert binary_search(data, target) == expected
assert binary_search([5], 5) == 0
assert binary_search([], 5) == -1
print("All binary search tests passed")
Worked example
Task: use a binary search on a sorted list of names to check whether "Li" is in the list, and show the values of low, high and mid.
names = ["Amy", "Jo", "Li", "Raj", "Sam", "Zoe"]
print(binary_search(names, "Li")) # 2
| Step | low |
high |
mid |
names[mid] |
Action |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | Li | Found at index 2 |
Strings are compared alphabetically, so binary search works on sorted text too. With "Sam":
| Step | low |
high |
mid |
names[mid] |
Action |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | Li | "Sam" > "Li", so low = 3 |
| 2 | 3 | 5 | 4 | Sam | Found at index 4 |
Exam tip: use <= in the loop condition and mid - 1 / mid + 1 when updating. Remember the sorted precondition. For the recursive version, state both base cases. Trace low, high and mid in a table.
Check yourself
Why is high set to mid - 1 and not mid?
The middle item has already been checked and isn't the target, so it is excluded; using mid could loop forever.
What are the two base cases of the recursive binary search?
The item is found at mid, or low > high (the range is empty, so it isn't there).
What is the maximum number of comparisons for 4000 items?
12 (2¹² = 4096 ≥ 4000).
Give three test cases for a binary search
Any three of: first item; last item; middle item; item not present; item smaller than all; item larger than all; one item; empty list.