Edexcel International Advanced Level Computer Science, point 5.2.2
Definition and function
A binary search finds an item in a sorted list by repeatedly comparing the target with the middle item and discarding the half that can't contain it.
Function: it finds a target's position much faster than a linear search on large sorted data.
Precondition: the list must be sorted. If it isn't, the method gives wrong results.
Method
- Set lower to the first index and upper to the last.
- Find the middle: DIV . (The book labels these L, M and H, for low, middle and high: the same as lower, mid and upper.)
- Compare the middle item with the target:
- Equal: found at
mid. - Target smaller: it must be in the lower half, so set
upper = mid - 1. - Target larger: it must be in the upper half, so set
lower = mid + 1.
- Equal: found at
- Repeat while lower is not greater than upper.
- If lower > upper, the target isn't in the list.
a. Iterative version
def binary_search(items, target):
lower = 0
upper = len(items) - 1
while lower <= upper:
mid = (lower + upper) // 2
if items[mid] == target:
return mid
elif target < items[mid]:
upper = mid - 1
else:
lower = mid + 1
return -1
Hand trace: find 23 in [4, 8, 15, 23, 42, 57, 61] (indices 0 to 6)
| Step | lower |
upper |
mid |
items[mid] |
Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | Found at index 3 |
Hand trace: find 57
| Step | lower |
upper |
mid |
items[mid] |
Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | 57 > 23, so lower = 4 |
| 2 | 4 | 6 | 5 | 57 | Found at index 5 |
Hand trace: find 10 (not in the list)
| Step | lower |
upper |
mid |
items[mid] |
Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | 10 < 23, so upper = 2 |
| 2 | 0 | 2 | 1 | 8 | 10 > 8, so lower = 2 |
| 3 | 2 | 2 | 2 | 15 | 10 < 15, so upper = 1 |
| 2 | 1 | lower > upper: not found, return -1 |
b. Recursive version
The same idea, but the function calls itself on the half that remains. The base cases are "found" and "lower > upper".
def bsearch(items, target, lower, upper):
if lower > upper: # base case: not found
return -1
mid = (lower + upper) // 2
if items[mid] == target: # base case: found
return mid
if target < items[mid]:
return bsearch(items, target, lower, mid - 1)
return bsearch(items, target, mid + 1, upper)
# start with: bsearch(items, 57, 0, len(items) - 1)
Trace of the recursive calls for 57 in the same list:
| Call | lower |
upper |
mid |
Result |
|---|---|---|---|---|
bsearch(..., 0, 6) |
0 | 6 | 3 | 57 > 23, calls with (4, 6) |
bsearch(..., 4, 6) |
4 | 6 | 5 | items[5] is 57, returns 5 |
The recursive version uses stack space for each call, but is clear and short.
Efficiency
- Each step halves the search area, so for items it needs at most rounded down, plus 1, comparisons (7 items: , rounded down to 2, plus 1 gives 3).
| Items | Maximum comparisons |
|---|---|
| 7 | 3 |
| 100 | 7 |
| 4 000 | 12 |
| 1 000 000 | 20 |
A linear search of 1 000 000 items may need 1 000 000. Doubling the list adds only one more comparison.
Benefits and drawbacks
- Benefits: very fast for large lists, and needs no extra memory (iterative).
- Drawbacks:
- The list must be sorted, and sorting costs time. It's only worth it if you search many times.
- Needs direct access by index (works on arrays and lists, not linked lists).
- More complex than linear search.
Worked example
Task: a sorted list of 12 names is searched for a target. What is the maximum number of comparisons? Compare with linear search.
- , so at most 4 comparisons are needed (, and ).
- A linear search needs up to 12.
Why can the target name not be found by binary search if the list is not sorted? The method assumes that all items below the middle are smaller and all above it are larger. In an unsorted list that isn't true, so it could discard the half that contains the target.
Exam tip: write lower, upper and mid in your trace table (with columns for any other variables the question gives, such as found) and update them correctly (mid - 1 and mid + 1). Remember the precondition: sorted data. State the stopping conditions: found, or lower > upper. For efficiency, say that each comparison halves the list.
Check yourself
What condition must be true of the data for a binary search?
It must be sorted.
In a binary search of [2, 5, 9, 14, 20], with lower = 0 and upper = 4, what is the first mid and its item?
mid = 2, and the item is 9.
When does the search stop and report "not found"?
When lower becomes greater than upper, so no items remain to search.
What is the maximum number of comparisons for 500 items?
9 (2⁸ = 256 is less than 500, and 2⁹ = 512 isn't, so log₂ 500 rounds down to 8, plus 1).
What are the two base cases in the recursive version?
The target is found at mid (return mid), and lower is greater than upper, so nothing is left to search (return -1).