Writing binary search as a loop
After this: Follow lo, hi and mid, and say what stays true on every pass of the loop.
On this page · 8 sections · 3 checks
In the last lesson you did binary search by hand: look at the middle, ignore one side, and repeat. A computer needs the same idea written as exact steps. This lesson turns it into a loop, one piece at a time.
Keeping track of what is left
In the guessing game you kept two numbers in your head: the smallest number still possible and the largest. At one point they were 26 and 49.
A search through an array keeps the same two numbers, but as indexes.
- are the first and the last index that could still hold the target. "lo" is short for low, and "hi" is short for high. Both ends are included.
- mid is the index in the middle of them: (lo + hi) // 2lo + (hi - lo) / 2. This division rounds down, so if lo is 0 and hi is 3, mid is 1.
The cells from lo to hi are called the range. It is the part of the array we have not ruled out.
One probe, three results
Each probe compares nums[mid] with the target. There are three possible results.
- They are equal. We have found the target, at index mid.
nums[mid]is too small. Then mid and everything to its left are too small, so we setlo = mid + 1.nums[mid]is too big. Then mid and everything to its right are too big, so we sethi = mid - 1.
Notice the + 1 and − 1. We have already looked at the cell at mid, and it is not the target, so it leaves the range.
A small search, step by step
Take the array from the last lesson, [10, 20, 30, 40, 50], and search for 40.
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 30 | Too small, so lo becomes 3 |
| 2 | 3 | 4 | 3 | 40 | Found at index 3 |
A search that finds the target is called a hit. A search that does not is called a miss. Here is a miss: the same array, searching for 35.
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 30 | Too small, so lo becomes 3 |
| 2 | 3 | 4 | 3 | 40 | Too big, so hi becomes 2 |
Now lo is 3 and hi is 2, so lo has passed hi. No cells are left between them, and we say the range is empty. Every cell has been ruled out, so 35 is not in the array.
This tells us when the loop should run: while lo <= hi. When lo equals hi, the range is one cell, and that cell still needs a look. When lo is greater than hi, the range is empty, and the search stops.
The code
def binary_search(nums, target): lo, hi = 0, len(nums) - 1 # if target is here, it is in nums[lo..hi] probes = 0 while lo <= hi: # the range still holds at least one cell mid = (lo + hi) // 2 probes += 1 if nums[mid] == target: return mid, probes if nums[mid] < target: lo = mid + 1 # mid and everything left of it are too small else: hi = mid - 1 # mid and everything right of it are too big return -1, probes # lo > hi: the range is empty, so it is not herestatic int probes = 0;
static int binarySearch(int[] nums, int target) { int lo = 0, hi = nums.length - 1; // if target is here, it is in nums[lo..hi] probes = 0; while (lo <= hi) { // the range still holds at least one cell int mid = lo + (hi - lo) / 2; // not (lo + hi) / 2: the traps lesson says why probes++; if (nums[mid] == target) return mid; if (nums[mid] < target) lo = mid + 1; // mid and everything left of it are too small else hi = mid - 1; // mid and everything right of it are too big } return -1; // lo > hi: the range is empty, so it is not here}Here is how to read it.
loandhistart at the two ends, so the range is the whole array.probesis a counter we added to measure the work. A real search does not need it.- The loop runs while the range holds at least one cell.
- Each pass works out mid, counts one probe, and then handles the three results from above.
- If the loop ends, the range is empty. The function returns −1, which is our signal for "not found".
- The function returns two values: the index and the probe count.The function returns the index, and it leaves the probe count in the variable probes.
Now we use it on a longer array.
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]index, probes = binary_search(nums, 23) # a hitprint(index, probes)index, probes = binary_search(nums, 7) # a missprint(index, probes)5 3 -1 3
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(binarySearch(nums, 23) + " " + probes); // a hitSystem.out.println(binarySearch(nums, 7) + " " + probes); // a miss5 3 -1 3
Here is the search for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91].
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 16 | Too small, so lo becomes 5 |
| 2 | 5 | 9 | 7 | 56 | Too big, so hi becomes 6 |
| 3 | 5 | 6 | 5 | 23 | Found at index 5 |
And here is the search for 7.
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 16 | Too big, so hi becomes 3 |
| 2 | 0 | 3 | 1 | 5 | Too small, so lo becomes 2 |
| 3 | 2 | 3 | 2 | 8 | Too big, so hi becomes 1 |
Now lo is 2 and hi is 1, so the range is empty, and 7 is not in the array. The miss took three probes, the same as the hit.
The rule that stays true
Look at the search for 23 again. After the first probe, what do you know? If 23 is in the array, it is somewhere in indexes 5 to 9. After the second probe, it is somewhere in indexes 5 to 6.
Each time, the same sentence is true: if the target is in the array, its index is between lo and hi. This is why the loop can be trusted.
- At the start, lo and hi cover the whole array, so the sentence is true.
- Each move removes only cells that cannot hold the target, so the sentence stays true.
- When the range is empty, there is nowhere left for the target to be. So the target is not in the array, and returning −1 is safe.
A rule that stays true on every pass of a loop has a name. It is called the loop's . "Invariant" means "does not change": lo and hi change on every pass, but the rule does not.
The highlighted lines in the code are the ones that keep this rule true: the starting range, the loop test and the two moves.
Watch it happen
Before each search, you will be asked to predict which cell the first probe reads. Tap it, then watch lo and hi close in.
- Binary search for 23Predict first: tap the cell the first probe reads. Then watch lo and hi close in on 23.
- Binary search for 2
- Binary search for 38
- 02
- 15
- 28
- 312
- 416
- 523
- 638
- 756
- 872
- 991
Run an operation to begin.
Check yourself
Searching [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] for 23. The first probe reads index 4, which holds 16. What are lo and hi after it?
binary_searchbinarySearch is the function from the lesson. Each line prints the index and the number of probes. What does this print?
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]index, probes = binary_search(nums, 23) # a hitprint(index, probes)index, probes = binary_search(nums, 7) # a missprint(index, probes)int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(binarySearch(nums, 23) + " " + probes); // a hitSystem.out.println(binarySearch(nums, 7) + " " + probes); // a missWhich rule is true at the start of every pass through the loop?
Connect
- Follow lo, hi and mid through a search, one probe at a time.
- State the rule that stays true on every pass, called the invariant: if the target is in the array, its index is between lo and hi, both included.
- Say why the loop runs while lo ≤ hi, and what lo > hi means.