Skip to content

Module 18 · Algorithms and Problem Solving — topic 9 of 18

Binary search

Fast searching in sorted data: the halving idea, iterative implementation with lo, hi and mid, tracing the steps, O(log n) performance, common off-by-one bugs, and the bisect module.

Beginner 10 min read·Lesson 269 of 306 in Python Programming

Learning objectives

  • Implement iterative binary search
  • Trace lo, hi and mid through a search
  • Use the bisect module for searching and insertion

Definition

Binary search finds a target in a sorted sequence by repeatedly comparing it with the middle element and discarding the half that cannot contain it. It takes O(log n) time.

Introduction

To find a word in a dictionary, you open it near the middle and decide which half to search next. In 20 steps you can find one entry among a million.

Why it matters

Binary search is one of the most important algorithms: databases, version-control tools and libraries use the same idea everywhere.

Detailed explanation

The data must be sorted. Binary search on unsorted data gives wrong answers.

Keep two bounds, lo and hi, around the part still possibly containing the target. Start with lo = 0 and hi = len(items) - 1.

Each step computes mid = (lo + hi) // 2. If items[mid] equals the target, return mid; if it is smaller, search the right half (lo = mid + 1); otherwise the left half (hi = mid - 1).

When lo > hi the range is empty and the target is not present.

Each step halves the range, so at most about log₂ n + 1 steps are needed: 10 for a thousand items, 20 for a million.

Off-by-one errors are common: use lo <= hi and move past mid with ±1, or the loop may never end.

The bisect module provides tested implementations: bisect_left and bisect_right find insertion points, insort inserts while keeping a list sorted.

Binary search also works on answers: 'find the smallest value for which a condition is true' if the condition changes from false to true only once.

Syntax

Python
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
  • Requires sorted data.
  • Halve the range each step.
  • lo <= hi and mid ± 1.

Code examples

Iterative binary search

Python
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(binary_search(nums, 23), binary_search(nums, 2), binary_search(nums, 40))
Output
5 0 -1

The bisect module

Python
import bisect
scores = [40, 55, 70, 85]
grades = "FDCBA"
def grade(score):
return grades[bisect.bisect_right(scores, score)]
print([grade(s) for s in [30, 55, 69, 85, 99]])
lst = [1, 3, 5]
bisect.insort(lst, 4)
print(lst)
Output
['F', 'C', 'C', 'A', 'A']
[1, 3, 4, 5]

More examples

Tracing the search

Python
import math
def traced_search(items, target):
lo, hi, step = 0, len(items) - 1, 0
while lo <= hi:
step += 1
mid = (lo + hi) // 2
print(f"step {step}: lo={lo} hi={hi} mid={mid} value={items[mid]}")
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print("found at", traced_search(nums, 72))
print(math.ceil(math.log2(1_000_000 + 1)))
Output
step 1: lo=0 hi=9 mid=4 value=16
step 2: lo=5 hi=9 mid=7 value=56
step 3: lo=8 hi=9 mid=8 value=72
found at 8
20

Step-by-step explanation

  • 16 is smaller than 72, so everything up to index 4 is discarded.
  • 56 is still smaller, so the search moves to indexes 8–9, where 72 is found on the third step.
  • The last line computes the maximum number of steps needed for a million sorted items: 20.

Expected output

Running “Tracing the search” prints exactly:

TextOutput
step 1: lo=0 hi=9 mid=4 value=16
step 2: lo=5 hi=9 mid=7 value=56
step 3: lo=8 hi=9 mid=8 value=72
found at 8
20

Practical applications

  • Looking up words in sorted dictionaries and indexes.
  • git bisect finding the commit that introduced a bug.

Best practices

  • Make sure the data is sorted.
  • Use bisect instead of writing your own in production code.
  • Test with the first, last and missing elements.

Common mistakes

Searching unsorted data

Avoid

binary_search([9, 2, 7, 4], 7)

Prefer

binary_search(sorted([9, 2, 7, 4]), 7)

The halving logic assumes order; on unsorted data it can miss the target.

Not moving past mid

Avoid

lo = mid

Prefer

lo = mid + 1

When lo and hi are adjacent, mid stays the same and the loop never ends.

Important notes

  • Sorting once costs O(n log n); it pays off when you search many times.

Key takeaways

  • Binary search halves a sorted range each step.
  • O(log n): about 20 steps for a million items.
  • bisect provides ready-made functions.

Try it yourself

  1. 1
    Write a recursive version of binary search.
  2. 2
    Use binary search to find the first position of a value that appears several times.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic