GCSE Python · Lesson 3 of 9

Binary search and invariants

OCR J277 2.1 / AQA 8525 algorithms

Search a sorted list using low, high and mid pointers.

← All GCSE Python lessons

Searching a sorted list

Binary search repeatedly compares the target with the middle item and discards the half that cannot contain it. The input must be sorted for that decision to be valid. Test first, middle, last and absent targets to check the boundary updates.

Watch out: Incorrectly changing low or high can skip a remaining item or cause an infinite loop. Trace both limits.

1 · Learn and predict

Read this worked example. Predict its output, run it in Python 3, and explain how variables change.

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

print(binary_search([2, 4, 6, 8, 10], 8))

2 · Build independently

Search a sorted list using low, high and mid pointers. Work from the starter code before comparing with the solution.

Download starter + solution ZIP ↓

For a stretch challenge: add meaningful test data, handle an edge case and explain one design decision.

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

numbers = [2, 4, 6, 8, 10, 12]
for target in [2, 11, 12]:
    print(target, binary_search(numbers, target))

The reference is one possible approach. Test your own program before comparing.

3 · Debug and explain

Question: What happens if the input list is unsorted?

Show explanation

We cannot know which half to discard, so results may be wrong.

4 · Check your understanding

Why is sorted order required?

5 · Reflect

Explain one test you used, one problem you solved and one improvement you would make.

This records completion only in this browser and does not certify mastery.

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

Always confirm the list is sorted before tracing binary search. After each middle-item comparison, identify exactly which half can be discarded and why.

Quick check: Can binary search reliably search an unsorted list?

Check: No. It relies on the ordering to eliminate half the remaining candidates.