Lesson 5 of 8
Algorithms: Lesson 5

Binary Search

The divide-and-conquer search algorithm that eliminates half the remaining candidates at every step. Far faster than linear search on large sorted lists - but it comes with a strict requirement.

50 minutes Step-through visualiser with low/mid/high pointers
Pseudocode style: Saved automatically

Imagine you are searching for a word in a printed dictionary. You do not start at page 1 and read every word - you open roughly in the middle. If your word would come before that page, you discard the second half entirely. If it would come after, you discard the first half. You repeat this, each time halving the remaining pages, until you find the word. You have just performed binary search. This is why it can find any word in a 1,000-page dictionary in just 10 steps.

Think about it: A binary search on a list of 1,000,000 items takes at most 20 steps (since 2^20 = 1,048,576). A linear search on the same list takes at most 1,000,000 steps. Why does binary search only work on sorted lists? What breaks if the list is not sorted?
Terms you need to know
Binary search
A search algorithm that repeatedly halves the search space by comparing the target to the middle element of the remaining range.
Sorted list
A list whose elements are arranged in order (ascending or descending). Binary search requires a sorted list to work correctly.
Low pointer
The index of the first element in the current search range. Starts at 0 and moves right when the target is higher than the mid element.
High pointer
The index of the last element in the current search range. Starts at n-1 and moves left when the target is lower than the mid element.
Mid pointer
The index of the middle element: mid = (low + high) DIV 2. The element at this position is compared to the target each iteration.
Logarithmic
Binary search complexity is O(log n) - the number of steps grows only logarithmically with list size, making it extremely efficient.
The algorithm step by step

Binary search maintains three pointers: low (leftmost boundary), high (rightmost boundary) and mid (middle index, calculated as (low + high) DIV 2). At each step:

StepActionResult
1Calculate mid = (low + high) DIV 2Identifies the middle element
2aIf myList[mid] = targetFound! Return mid and stop.
2bIf target < myList[mid]Target is in the left half. Set high = mid - 1.
2cIf target > myList[mid]Target is in the right half. Set low = mid + 1.
3If low > highSearch space is empty. Target not found. Return -1.
4 (loop)Return to step 1Repeat with the new, smaller search range.
Why it must be sorted

Binary search relies entirely on the comparison in steps 2b and 2c. When we see that target < myList[mid], we conclude the target must be in the left half - but only if the list is sorted in ascending order. If the list is unsorted, elements to the left of mid could be larger than target, and we would be discarding half the list incorrectly. The entire algorithm breaks down on an unsorted list.

Writing binary search
// Binary search - returns index of target or -1 (AQA)
SUBROUTINE binarySearch(myList, target)
    low  0
    high  LEN(myList) - 1
    found  FALSE
    index  -1
    WHILE low <= high AND found = FALSE
        mid  (low + high) DIV 2
        IF myList[mid] = target THEN
            found  TRUE
            index  mid
        ELSEIF target < myList[mid] THEN
            high  mid - 1    // Discard right half
        ELSE
            low  mid + 1    // Discard left half
        ENDIF
    ENDWHILE
    RETURN index
ENDSUBROUTINE
# Binary search - returns index of target or -1 (OCR)
function binarySearch(myList, target)
    low = 0
    high = len(myList) - 1
    found = false
    index = -1
    while low <= high and found == false
        mid = (low + high) DIV 2
        if myList[mid] == target then
            found = true
            index = mid
        elseif target < myList[mid] then
            high = mid - 1
        else
            low = mid + 1
        end if
    end while
    return index
endfunction
Exam angle

The most common exam error is setting high = mid instead of high = mid - 1 (and low = mid instead of low = mid + 1). Using mid instead of mid ± 1 can cause an infinite loop because the search space never shrinks when low = mid = high. Always use mid - 1 and mid + 1. Also know: DIV means integer division (discard the remainder). (7 + 4) DIV 2 = 5, not 5.5.

Tracing binary search step by step

Trace binary search for target = 23 in myList = [2, 5, 8, 12, 16, 23, 38, 47]:

IterationlowhighmidmyList[mid]ComparisonAction
107(0+7) DIV 2 = 31223 > 12low = 3 + 1 = 4
247(4+7) DIV 2 = 52323 = 23Found! Return index 5.

Only 2 comparisons to find 23 in an 8-element list. Linear search would have needed 6 comparisons to reach index 5.

Now trace for target = 10 (not in list): myList = [2, 5, 8, 12, 16, 23, 38, 47]

IterationlowhighmidmyList[mid]ComparisonAction
10731210 < 12high = 3 - 1 = 2
2021510 > 5low = 1 + 1 = 2
3222810 > 8low = 2 + 1 = 3
Exit32--low > high (3 > 2)Return -1 (not found)
Binary vs linear search
PropertyLinear searchBinary search
RequirementNone - works on any listList must be sorted in order
Best case1 comparison (target is first)1 comparison (target is the first mid)
Worst casen comparisonslog2(n) comparisons
Average casen/2 comparisonslog2(n) comparisons
n = 100Up to 100Up to 7
n = 1,000,000Up to 1,000,000Up to 20
ComplexityO(n) - linearO(log n) - logarithmic
Exam angle

The most-tested comparison question: "State one advantage of binary search over linear search and one advantage of linear search over binary search."
Binary search advantage: Much fewer comparisons needed for large lists (O(log n) vs O(n)).
Linear search advantage: Does not require the list to be sorted.

Watch binary search divide and conquer

The list is already sorted. Enter a target and press Start to watch binary search step through. Orange = mid (being compared). Blue = low marker. Green = high marker. Faded = eliminated from search range.

Enter a target and press Start. List: [2, 5, 8, 12, 16, 23, 38, 47]

Test yourself

1. Binary search is performed on [1, 4, 7, 10, 15, 19, 25, 30]. What is the first mid index calculated? (low=0, high=7)

mid = (0 + 7) DIV 2 = 7 DIV 2 = 3. The element at index 3 is 10. DIV means integer division - always round down.

2. A binary search is looking for target = 4 in [1, 4, 7, 10, 15, 19, 25, 30]. After comparing to myList[3]=10, what happens?

Since 4 < myList[3]=10, the target must be in the left half (indices 0 to 2). We set high = mid - 1 = 3 - 1 = 2. The right half is eliminated. The new search range is indices 0 to 2.

3. What is the maximum number of comparisons binary search needs to find an item in a sorted list of 128 items?

log2(128) = 7 (since 2^7 = 128). Binary search halves the search space each time, so it needs at most log2(n) comparisons. Compare to linear search's worst case of 128 comparisons.

4. Why does binary search require the list to be sorted?

When binary search finds that target < myList[mid], it concludes the target must be in the left half and discards the right. This is only valid if the list is sorted - otherwise, the target could be anywhere in the discarded half.

5. When binary search exits because low > high, what does this mean?

When low exceeds high, there are no elements left in the current search range. Every element has been either compared or logically eliminated. The target is not in the list, so -1 is returned.
Challenge question

A developer has a list of 10,000 customer records sorted by customer ID. New customers are added daily in random order (so the list must be resorted each time before binary search can be used). At what point would it be more efficient to stop resorting for binary search and just use linear search instead? What factors would affect this decision?

This is a trade-off question with no single correct numerical answer, but the reasoning matters:

Binary search: Requires sorting first (sorting 10,000 items using an efficient sort is approximately 10,000 x log(10,000) = ~130,000 operations), then each search is ~14 comparisons.

Linear search: No sorting needed. Each search is up to 10,000 comparisons.

Key insight: If you only search the list once after each sort, binary search may not be worth it (130,000 operations to sort + 14 to search vs 10,000 for linear). But if you search many times between updates, binary search wins massively. The break-even point depends on: (1) how often the list is searched between updates, (2) the cost of the sorting algorithm used, and (3) whether the list can be maintained in sorted order as items are inserted (insertion into a sorted list can be done efficiently).
Printable Worksheets

Practice what you have learned

Three levelled worksheets. Download, print and complete offline.

Recall
Binary Search Fundamentals
Define terms, calculate mid values and state maximum comparisons for given list sizes.
Download
Apply
Tracing Binary Search
Complete full trace tables for three binary searches with varying targets (found, not found, edge cases).
Download
Exam Style
Exam-Style Questions
Complete pseudocode, compare to linear search, justify algorithm choice and calculate maximum comparisons for given scenarios.
Download
Lesson 5 - Algorithms
Binary Search
Starter activity
The "number guessing game" starter: tell students you are thinking of a number between 1 and 100. They guess; you say higher, lower or correct. Debrief: a student who uses binary search (always guessing the midpoint of the remaining range) will find it in at most 7 guesses. A student who guesses randomly may need up to 100. This directly motivates the power of binary search and makes the algorithm intuitive before any pseudocode is seen.
Lesson objectives
1
Explain why binary search requires a sorted list.
2
Describe the role of the low, high and mid pointers in binary search.
3
Calculate the mid index given low and high values using integer division.
4
Trace binary search step by step for a given list and target, showing all pointer updates.
5
Compare binary and linear search in terms of efficiency and requirements.
Key vocabulary
Binary search
Divides search range in half each step. Requires sorted list. O(log n) worst case.
Mid index
mid = (low + high) DIV 2. Integer division - always round down.
low > high
Exit condition - search space exhausted. Target not found. Return -1.
Discussion questions
Why does binary search use mid - 1 and mid + 1 rather than just mid? What would happen if you used mid?
If you have an unsorted list and must use binary search, what extra step is required first? Is this always worth it?
Binary search has O(log n) worst case. What does "logarithmic" mean in practical terms?
Exit tickets
Calculate: binary search on a 1024-item list. How many comparisons maximum? [1 mark]
State one advantage of linear search over binary search. [1 mark]
Trace binary search for target=7 in [1,3,7,9,12]. Show each step. [3 marks]
Homework suggestion
Write pseudocode for a binary search that finds the first occurrence of a value in a list where that value may appear multiple times. Explain how this differs from the standard binary search which finds any occurrence.