Code

Binary Search

Linear search checks items one by one: up to n steps, O(n).

If the list is sorted, you can do much better. Look at the middle item:

  • If it's the target, you're done.
  • If the target is bigger, it can only be in the right half.
  • If it's smaller, it can only be in the left half.

Each step throws away half the list. A million items take only about 20 steps, because 2²⁰ ≈ 1,000,000. That's O(log n).

lo, hi = 0, len(items) - 1      # the part still worth searching
while lo <= hi:
    mid = (lo + hi) // 2
    ...                         # move lo or hi past mid

Pip tip: Python's bisect module does binary search for you in real code. Writing it once yourself is the best way to understand it, and it's a classic interview question!

Assignment

Write binary_search(items, target):

  1. items is a list sorted from smallest to largest.
  2. Return the index of target, or -1 if it isn't there.
  3. Use the halving strategy. Don't loop over every item (the tests check!).