How Binary Search Finds an Item in a Sorted List
Learn how binary search halves a sorted list to find a value fast, trace it step by step, and write it in a few lines of Python.
Computer Science
By the end of this lesson you will be able to explain how binary search finds a value in a sorted list, trace it by hand on a small example, write it in a few lines of Python, and explain why it needs far fewer comparisons than checking every item one by one.
The words you need
A list is an ordered collection of values, such as numbers. Each value sits at a position called its index. In Python and many other languages, the first index is 0, the second is 1, and so on.
The target is the value we are looking for. A comparison is one check where we look at an item and compare it with the target. We count comparisons to measure how much work a search does.
The simplest way to search is linear search: start at the first item and check each one in turn until you find the target or run out of items. It always works, but on a long list it can take a lot of checks. Binary search is faster, but it has one firm requirement: the list must be sorted, meaning the values go from smallest to largest.
The big idea: check the middle, throw away half
Think about looking up a word in a paper dictionary. You do not read from page one. You open near the middle, see whether your word comes before or after that page, and ignore the half that cannot contain it. Binary search does exactly this.
We keep track of the part of the list still worth searching using two indexes: low (the start of that part) and high (the end). At each step we look at the middle item. If it equals the target, we are done. If the middle item is smaller than the target, the target can only be to the right, so we move low just past the middle. If the middle item is larger, the target can only be to the left, so we move high just before the middle. If low ever passes high, there is nothing left to search, and the target is not in the list.
Worked example: tracing it by hand
Here is a sorted list of nine numbers: 3, 8, 12, 17, 23, 31, 42, 56, 64. Their indexes run from 0 to 8. We want to find 56. To find the middle, add low and high and divide by 2, rounding down.
- Step 1: low = 0, high = 8, so middle = 4. The item at index 4 is 23. 23 is smaller than 56, so set low = 5.
- Step 2: low = 5, high = 8, so middle = (5 + 8) / 2 = 6.5, rounded down to 6. The item is 42. 42 is smaller than 56, so set low = 7.
- Step 3: low = 7, high = 8, so middle = 7. The item is 56. It matches, so the answer is index 7.
Binary search needed 3 comparisons. Linear search would have checked 3, 8, 12, 17, 23, 31, 42 and then 56: that is 8 comparisons.
Now try a target that is missing: 20. Middle 4 holds 23, which is too big, so high = 3. Middle 1 holds 8, too small, so low = 2. Middle 2 holds 12, too small, so low = 3. Middle 3 holds 17, too small, so low = 4. Now low (4) is greater than high (3), so the search stops: 20 is not in the list. That took 4 comparisons.
Writing it in Python
The code follows the steps above exactly. It returns the index of the target, or -1 if the target is not found. The // operator divides and rounds down to a whole number, which is how we get the middle index.
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
numbers = [3, 8, 12, 17, 23, 31, 42, 56, 64]
print(binary_search(numbers, 56)) # prints 7
print(binary_search(numbers, 20)) # prints -1Notice the + 1 and - 1 when moving low and high. We already know the middle item is not the target, so we leave it out. Forgetting this is a common mistake and can make the loop run forever.
Why so few comparisons?
Each comparison cuts the part still to search roughly in half. Start with 16 items and the worst case shrinks the search like this:
So the question becomes: how many times can you halve the list before only one item is left? Since 2 multiplied by itself 10 times is 1,024, a list of 1,000 items needs at most 10 comparisons. Since 2 to the power 20 is 1,048,576, a list of one million items needs at most 20. Linear search on that same list could need one million comparisons.
Mathematicians call this count the base 2 logarithm: the number of times you multiply 2 by itself to reach a number. Doubling the list size adds only one extra comparison to binary search, while it doubles the worst case for linear search. The price is that the list must be sorted first.
Try it yourself
- Trace binary search on the list 3, 8, 12, 17, 23, 31, 42, 56, 64 for the target 8. Write down low, high and the middle index at each step. How many comparisons did it take?
- Why does binary search fail on the unsorted list 9, 2, 7, 4, 5 when searching for 2? Trace it to see what goes wrong.
- What is the largest number of comparisons binary search needs for a sorted list of 100 items? Explain using powers of 2.
- Change the Python function so it also prints the middle item at every step, then run it on a target that is missing from the list.
