Unit 4: Algorithms · Linear and binary search

Article

Binary search

8 min read

Think of a number from 1 to 100 and let a friend guess. A smart friend does not try 1, then 2, then 3. They say "50". You say "higher". They say "75". You say "lower". Each answer throws away half of the numbers left, so seven guesses are always enough. That is binary search.

Check the middle, throw away half

Binary search has one strict rule: the list must be sorted (here, smallest first). Because the list is in order, one look at the middle tells you which half to keep. The steps:

  1. Look at the middle item of the part still possible.
  2. If it equals the target, you are done: found.
  3. If the target is bigger, throw away the middle item and everything before it.
  4. If the target is smaller, throw away the middle item and everything after it.
  5. Repeat with what is left. If nothing is left, the target is not in the list.

Here is a sorted list of 15 numbers. We search for 47:

CheckItems still possibleMiddle itemWhat we learn
13 8 12 17 21 25 30 34 41 47 52 58 63 70 77 (15 items)3447 is bigger than 34: keep the right part
241 47 52 58 63 70 77 (7 items)5847 is smaller than 58: keep the left part
341 47 52 (3 items)47equal: found

Three checks. A linear search would need 10, because 47 is the tenth item.

The algorithm

Two variables, low and high, hold the first and last position of the part still possible. The middle is halfway between them.

AP pseudocode
PROCEDURE binarySearch(aList, target)
{
    low ← 1
    high ← LENGTH(aList)
    REPEAT UNTIL(low > high)
    {
        middle ← (low + high - (low + high) MOD 2) / 2
        IF(aList[middle] = target)
        {
            RETURN(true)
        }
        IF(aList[middle] < target)
        {
            low ← middle + 1
        }
        ELSE
        {
            high ← middle - 1
        }
    }
    RETURN(false)
}

Binary search

truefalsetruefalsetruefalselow ← 1, high ←LENGTH(aList)low > high?Return falsemiddle ← halfwaybetween low and highaList[middle] =target?Return trueaList[middle] <target?low ← middle + 1high ← middle - 1
Each trip round the loop discards the middle item and one whole side. When low passes high, nothing is left.

Trace the search for 47 in the same list. Indexes run from 1 to 15:

ChecklowhighmiddleaList[middle]Result
1115834smaller than 47, so low ← 9
29151258bigger than 47, so high ← 11
39111047equal: RETURN(true)

Now search for 10, which is not in the list. The middle items are 34, 17, 8 and 12. After the fourth check low is 3 and high is 2, so low > high: nothing is left, and the procedure returns false. Run the Python version and change the target:

Runs in your browser

Python counts from 0, so low starts at 0 and high at len(a_list) - 1. // divides and rounds down. while low <= high is the opposite of REPEAT UNTIL(low > high). The number of checks is the same.

Check your understanding

A binary search looks for 17 in the sorted list [2, 5, 8, 11, 14, 17, 20]. Which item does it check first?

How many checks at most?

Each check keeps at most half of the items. For 1,000 items, keep halving (drop any remainder):

1,000 → 500 → 250 → 125 → 62 → 31 → 15 → 7 → 3 → 1 → 0

That is 10 halvings, so binary search needs at most 10 checks for 1,000 items. Linear search could need 1,000. Look how slowly the checks grow:

Items in the listLinear search, worst caseBinary search, worst case
10104
1001007
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

Every time the list doubles, binary search needs just one more check. In other words, k checks are enough for up to 2ᵏ − 1 items. So find the smallest k where 2ᵏ is bigger than the number of items.

Checks12345678910
Up to this many items1371531631272555111,023

For a list of 200: 2⁷ = 128 is not bigger than 200, but 2⁸ = 256 is. So at most 8 checks. For exactly 128 items you also need 8, not 7.

Check your understanding

A sorted list has 60 items. What is the maximum number of items a binary search checks?

It must be sorted

Binary search trusts the order. In an unsorted list the middle item tells you nothing, and the search can throw away the half that holds the target. Search [9, 2, 14, 5, 20, 7, 11] for 14 (the third item):

ChecklowhighmiddleaList[middle]Result
11745smaller than 14, so low ← 5
25767smaller than 14, so low ← 7
377711smaller than 14, so low ← 8

Now low > high, so it returns false. But 14 is in the list, and there is no error message to warn you.

Sorting has a cost

An unsorted list must be sorted first, and sorting takes many more steps than one linear search. So:

  • Search an unsorted list once: use linear search.
  • Search the same list many times: sort it once, then every search is fast.

Common mistakes

  • Using binary search on an unsorted list. It can say "not found" for an item that is there.
  • Keeping the middle item. Set low ← middle + 1 or high ← middle - 1, never middle.
  • Thinking you check half of the items. You check only a tiny number: 20 for a million.
  • Saying 128 items need 7 checks. They need 8.
  • Using a list sorted the wrong way round. The code above expects smallest first. A list sorted from largest to smallest breaks it.

On the exam

Two questions appear again and again. "Which search needs the list to be sorted?" (binary, not linear). And "What is the maximum number of checks for a sorted list of n items?" (halve until 0, or find the smallest k with 2ᵏ bigger than n). Some questions ask you to trace a few steps: write low, high and middle in a table, as above.

Key words

Binary search: finds a target in a sorted list by checking the middle item and discarding half of the rest, again and again.

Sorted: in order, for example from smallest to largest.

AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site. All lessons and questions here are written by JrCodex.