B2.4 · Searching · Covered

Binary search

Use sorted data to rule out half of the remaining candidates at each step.

55 minutes

For this lesson

Watch binary search

Target 42
Sorted values · indices underneath8 candidates
RemainingRuled outChecking

Start with all eight values. Check the middle index, rounding down.

low = 0mid = —high = 7

Python implementation

Highlight = the line just executed. Skipped branches stay unhighlighted.

def binary_search(items, target):    low = 0    high = 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

Ready to call binary_search(items, 42).

0 values checked

By the end of this lesson

  • Explain why binary search requires sorted input.
  • Trace low, mid and high through successful and unsuccessful searches.
  • Implement binary search and test its boundaries.

Use these activities to review the topic at your own pace. Timings are approximate.

Review the lesson

01 · 5 minutes

Retrieve linear search

Describe the first-match algorithm. How many comparisons might it need for an absent target in a list of 1,000 values?

02 · 10 minutes

Find the middle

Search [3, 8, 12, 17, 23, 31, 42, 56] for 31 by hand. Use zero-based indices, low = 0, high = len(items) - 1 and mid = (low + high) // 2. After a failed comparison, explain which half can be discarded.

03 · 15 minutes

Trace two searches

Build a table with iteration, low, high, mid, items[mid] and next action. Trace a successful search for 31 and an unsuccessful search for 20. Record why the loop stops in each case.

04 · 20 minutes

Implement and test

Write binary_search(items, target), returning a matching index or -1. Continue while low <= high. Test an empty list, a singleton, first and last values, and an absent value. Compare expected and actual results.

05 · 5 minutes

Explain your decisions

Explain why the next boundary is mid + 1 or mid - 1, rather than mid. State what you can guarantee if duplicate values occur.

Before you leave

Exit question

What makes the search interval shrink, and why would unsorted input break the reasoning?

Homework for this topic

Due 21 Sept 2026 · Problems 1 and 2 + reading · Assigned

Weekend homework: Problems 1 and 2 + reading

Complete Problems 1 and 2 in the algorithms handout, then read the textbook’s binary-search section. Have your work ready for Monday, 21 September.