Module 4 · Smart Patterns for Lists · Lesson 13 of 40
Binary search
Find a value in a sorted list by halving the search area each step: O(log n).
In this lesson · about 22 minutes
- Write binary search with low, high and mid
- Explain why it needs a sorted list
- Use 'binary search on the answer' for yes/no questions
Binary search is the phone-book trick from lesson 1. It only works on a sorted list.
- Keep two pointers,
lowandhigh, around the part that might still hold the target. - Look at the middle:
mid = (low + high) // 2. - If it is the target, done. If the middle is too small, the target must be to the right:
low = mid + 1. If it is too big:high = mid - 1. - Repeat while
low <= high. If they cross, the target isn't there.
Each look throws away half of what is left, so it takes about log₂ n looks: O(log n). For a million items, that's about 20.
Try it · see it work
Binary search, step by step
Try a target that is in the list, like 60, and one that is not, like 50.
Step 1 of 4Look for 60. The whole list is still possible: low = 0, high = 14.
Try it: binary search in Python
Exercise
Write binary search
Finish binary_search(nums, target). Return the index of the target, or -1 if it is not in the sorted list.
Binary search on the answer
Binary search is not only for lists. You can use it whenever the answer is a number and you can ask a yes/no question that flips once: "no, no, no, yes, yes, yes".
Example: what is the whole-number square root of 50 (rounded down)? Ask "is x × x ≤ 50?" for x between 0 and 50. The answer is yes up to 7 and no from 8 on. Binary search finds the last "yes" in a few steps, without testing every number.
The same trick solves "what is the smallest speed that finishes the job in time?" and many other puzzles.
Exercise
Square root by binary search
Write int_sqrt(n) that returns the largest whole number x with x * x <= n, using binary search between 0 and n. Don't use math.sqrt or ** 0.5.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.