Binary search
In a sorted array, compare the middle item of the range with the value you want and throw away half of the range each time.
Binary search only works on a sorted array. The range a[low..high] is where target can still be. In each
round, look at the middle item a[mid]:
- Time:
O(log n) - Space:
O(1) - CLRS, section 2.3
- Johnsonbaugh, chapter 7
Ten sorted numbers; 9 is found after halving the range three times.
def binary_search(a, target):low = 0high = len(a) - 1while low <= high:mid = (low + high) // 2if a[mid] == target:return midif a[mid] < target:low = mid + 1else:high = mid - 1return -1
Start
Local variables
Orange = changed in this step
a list
Call stack
- binary_search()line 1
How the work grows with input size
Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- comparisons
- probe
- current input (n=10)
Show as a table
| n | comparisons | probe |
|---|---|---|
| 4 | 3.6 | 2.1 |
| 6 | 4.8 | 2.7 |
| 8 | 4.9 | 2.8 |
| 10 | 5.1 | 2.8 |
| 12 | 6.5 | 3.6 |
| 14 | 6 | 3.3 |
| 16 | 5.6 | 3.1 |
Explanation
The idea
Binary search only works on a sorted array. The range a[low..high] is where target can still be. In each
round, look at the middle item a[mid]:
- If it equals
target, you are done. - If it is smaller,
targetcan only be in the right half:low = mid + 1. - If it is larger, only in the left half:
high = mid − 1.
When low > high the range is empty and target is not in the array; the function returns −1.
Cost
Each round halves the range, so at most ⌊log₂ n⌋ + 1 rounds are needed: at most 10 for a thousand items, 20 for a
million. The extra memory is O(1).
Why the array must be sorted
Throwing away half of the range is only correct if every item left of a[mid] is smaller or equal and every item to
its right is larger or equal. The input validator does not accept an unsorted array.
What to watch in the trace
- The blue band is the range
low..high, and the dashed blue line is the height oftarget. - The
low,midandhigharrows move under the bars; watch the range halve every round. - The "target repeats" input shows that this version does not necessarily find the first copy.