Skip to content
dreamcode
dreamcode
Map
Binary search
Lesson 58 of 77
+15 XP on finish
ALGORITHMSChapter 10 · Algorithms and Problem Solving

Searching

Linear search checks items one by one: O(n), and it works on any list. Binary search needs a sorted list, but it is O(log n): look at the middle item, then throw away the half that cannot contain the target, and repeat. A million sorted items need at most about 20 checks.

Worked example

How it reads

  • low and high mark the part of the list that could still hold the target
  • Each step discards half, so 200 items take at most 8 steps
  • When low passes high, the target is not there
Common mistakes
  • Running binary search on an unsorted list silently gives wrong answers.
Cloud tip: Python's bisect module has binary search built in: bisect.bisect_left(items, target).
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Rewrite find as a binary search. It should still print 6 then -1.

Press Run to check your work.