Module 18 · Algorithms and Problem Solving — topic 9 of 18
Binary search
Fast searching in sorted data: the halving idea, iterative implementation with lo, hi and mid, tracing the steps, O(log n) performance, common off-by-one bugs, and the bisect module.
Learning objectives
- Implement iterative binary search
- Trace lo, hi and mid through a search
- Use the bisect module for searching and insertion
Definition
Binary search finds a target in a sorted sequence by repeatedly comparing it with the middle element and discarding the half that cannot contain it. It takes O(log n) time.
Introduction
To find a word in a dictionary, you open it near the middle and decide which half to search next. In 20 steps you can find one entry among a million.
Why it matters
Binary search is one of the most important algorithms: databases, version-control tools and libraries use the same idea everywhere.
Detailed explanation
The data must be sorted. Binary search on unsorted data gives wrong answers.
Keep two bounds, lo and hi, around the part still possibly containing the target. Start with lo = 0 and hi = len(items) - 1.
Each step computes mid = (lo + hi) // 2. If items[mid] equals the target, return mid; if it is smaller, search the right half (lo = mid + 1); otherwise the left half (hi = mid - 1).
When lo > hi the range is empty and the target is not present.
Each step halves the range, so at most about log₂ n + 1 steps are needed: 10 for a thousand items, 20 for a million.
Off-by-one errors are common: use lo <= hi and move past mid with ±1, or the loop may never end.
The bisect module provides tested implementations: bisect_left and bisect_right find insertion points, insort inserts while keeping a list sorted.
Binary search also works on answers: 'find the smallest value for which a condition is true' if the condition changes from false to true only once.
Syntax
- Requires sorted data.
- Halve the range each step.
- lo <= hi and mid ± 1.
Code examples
Iterative binary search
5 0 -1
The bisect module
['F', 'C', 'C', 'A', 'A'] [1, 3, 4, 5]
More examples
Tracing the search
step 1: lo=0 hi=9 mid=4 value=16 step 2: lo=5 hi=9 mid=7 value=56 step 3: lo=8 hi=9 mid=8 value=72 found at 8 20
Step-by-step explanation
- 16 is smaller than 72, so everything up to index 4 is discarded.
- 56 is still smaller, so the search moves to indexes 8–9, where 72 is found on the third step.
- The last line computes the maximum number of steps needed for a million sorted items: 20.
Expected output
Running “Tracing the search” prints exactly:
Practical applications
- Looking up words in sorted dictionaries and indexes.
- git bisect finding the commit that introduced a bug.
Best practices
- Make sure the data is sorted.
- Use bisect instead of writing your own in production code.
- Test with the first, last and missing elements.
Common mistakes
Searching unsorted data
Avoid
Prefer
The halving logic assumes order; on unsorted data it can miss the target.
Not moving past mid
Avoid
Prefer
When lo and hi are adjacent, mid stays the same and the loop never ends.
Important notes
- Sorting once costs O(n log n); it pays off when you search many times.
Key takeaways
- Binary search halves a sorted range each step.
- O(log n): about 20 steps for a million items.
- bisect provides ready-made functions.
Try it yourself
- 1Write a recursive version of binary search.
- 2Use binary search to find the first position of a value that appears several times.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?