Binary Search

In a sorted list, look at the middle and throw away the half that cannot contain the target. Ten items take only three checks.

Python · intermediate · 7 min · 19 steps · free

What you'll learn

binary_search.py

def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        mid = (low + high) // 2
        if items[mid] == target:
            return mid
        elif items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

sorted_nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(binary_search(sorted_nums, 23))

Step by step

  1. Python defines the function binary_search(). Its body does not run yet: it runs each time the function is called.
  2. sorted_nums is created and points to a new list: [2, 5, 8, 12, 16, 23, 38, 56, …].
  3. Python calls binary_search(), with items = [2, 5, 8, 12, 16, 23, 38, 56, …] and target = 23. It gets its own names.
  4. low and high mark the part of the list where 23 could still be: all of it.
  5. low <= high is true, so the loop body runs.
  6. The middle index is 4, which holds 16.
  7. items[mid] == target is false, so the block under it is skipped.
  8. items[mid] < target is true, so the block under it runs.
  9. 16 is less than 23, so 23 must be to the right. Everything up to the middle is thrown away: low = 5.
  10. low <= high is true, so the loop body runs.
  11. mid changes from 4 to 7.
  12. items[mid] == target is false, so the block under it is skipped.
  13. items[mid] < target is false, so the block under it is skipped.
  14. 56 is bigger than 23, so drop the right half: high = 6.
  15. low <= high is true, so the loop body runs.
  16. mid changes from 7 to 5.
  17. items[mid] == target is true, so the block under it runs.
  18. items[5] is 23: found in 3 checks instead of 6.
  19. binary_search() has finished, so its names are gone. It prints 5.

Common mistakes

Best practices

Key takeaways

Check yourself

About how many checks for 1,000 items?

Answer: 10. 2¹⁰ = 1024.

Target smaller than items[mid]?

Answer: high = mid - 1

·

More in Complexity and Searching