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.

  1. Keep two pointers, low and high, around the part that might still hold the target.
  2. Look at the middle: mid = (low + high) // 2.
  3. 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.
  4. 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.

A plain left-to-right search would need 12 checks.
low30
81
122
173
214
255
306
347
418
479
5210
6011
6812
7513
high8314

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

Question 1

1.What must be true about a list before binary search works?

Question 2

2.nums[mid] is smaller than the target. What next?

Question 3

3.About how many looks does binary search need for 1,000 items?

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

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.