A friend thinks of a number from 1 to 100. Each time you guess, they only say "higher", "lower" or "right". You guess 50 and hear "higher". That means 1 to 50 are no longer possible, without guessing them one by one. If you always guess the middle number, how many guesses do you need at most to be sure you find it? Keep your answer in mind.
Guessing the middle and throwing away half like this is called binary search. Binary search looks for a value in an array that is already sorted, which means its items are in order from small to large. It works like this: check the number in the middle, then drop (throw away) the half that can't hold the target (the value you are looking for). With every step, the data that's left is cut in half. In the guessing game, the numbers 1 to 100 are the array, and your friend's number is the target.
How it works
Look for 13 in an array arr that holds [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] (10 numbers, index 0 to 9). left and right are the indexes of the left edge and the right edge of the part of the array that could still hold the target. mid is the index in the middle of that part.
| Step | left |
right |
mid |
arr[mid] |
Decision |
|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 9 | 9 < 13, drop the left: left = 5 |
| 2 | 5 | 9 | 7 | 15 | 15 > 13, drop the right: right = 6 |
| 3 | 5 | 6 | 5 | 11 | 11 < 13, drop the left: left = 6 |
| 4 | 6 | 6 | 6 | 13 | equal, found at index 6 |
Here is the code in JavaScript:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1; // drop the left half
else right = mid - 1; // drop the right half
}
return -1; // not there
}
const arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
console.log(binarySearch(arr, 13)); // 6
console.log(binarySearch(arr, 4)); // -1
left = 0andright = arr.length - 1(the last index): at first, every index is still possible.while (left <= right)repeats as long as there's something left to check.<=means "is smaller than or equal to". Use<=, not<: when one number is left (leftequalsright), that number still has to be checked. With<, that number is skipped: in the table above, step 4 never runs and 13 is not found.Math.floor(...)rounds down.(5 + 6) / 2gives5.5, but an index has to be a whole number, somidbecomes 5.- Is
arr[mid]smaller than the target? Then the target must be to the right ofmid, so the left edge moves:left = mid + 1. Bigger? The target is to the left, so the right edge moves:right = mid - 1. The+ 1and- 1are there becausemidhas already been checked. - Once
lefthas passedright, there's nothing left to check, so the result is-1.
One step is one check of arr[mid]. The table above has 4 steps.
The rule: the data must be sorted
Binary search only gives the right result on data that's already sorted. When the middle number is smaller than the target, this code drops the left half, because in sorted data every number to the left of the middle is even smaller. On shuffled data, the numbers to the left of the middle are not always smaller. No error appears, but the result is wrong. binarySearch([5, 1, 9, 3, 7], 1) returns -1, even though 1 is at index 1. The search checks 9, then 5. Both are bigger than 1, so the search moves left and stops without checking index 1.
Why it's so fast
Every step throws away half of what's left. 100 numbers become 50, 25, 12, 6, 3, then 1: at most 7 steps. So in the 1-to-100 guessing game, 7 guesses are always enough.
| Amount of data | Linear search, at most | Binary search, at most |
|---|---|---|
| 100 | 100 steps | 7 steps |
| 1,000 | 1,000 steps | 10 steps |
| 1,000,000 | 1,000,000 steps | 20 steps |
The amount of data is called n. Binary search is written O(log n): double the data, and it takes just one more step. log n means how many times n can be halved until 1 is left. Compare that with linear search, which is O(n): double the data, and the steps double too.
⚠️ Why does your binary search loop forever or miss?
left = midwithout+ 1. Whenleftandrightare side by side,midalways equalsleft. Soleft = middoesn't move the left edge, and the loop never stops.- Forgetting
Math.floor.arr[3.5]isundefined(there is no item there), so the comparison goes wrong and the target is never found. - Printing the number directly. In the exercise,
console.log(3)does print 3, but what's being tested is the result ofbinarySearch(...). Print the result of calling the function.
TL;DR: Binary search looks for a value (the target) in an array that is already sorted. left and right are the edges of the part that could still hold the target. Check the item in the middle, mid = Math.floor((left + right) / 2): equal means found, smaller than the target means left = mid + 1, bigger means right = mid - 1. Repeat while left <= right, then return -1 if nothing is left. Every step drops half the data, so it's O(log n): 1,000 items take about 10 steps, 1 million about 20. If the data isn't sorted, the result is wrong with no error.
⚡ Check the middle, drop half
Write:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1; // drop the left half
else right = mid - 1; // drop the right half
}
return -1; // not there
}
Meaning: Binary search looks for target in an array that is already sorted. left and right are the edges of the part that could still hold the target, and mid is the index in the middle of it. If arr[mid] is smaller than the target, drop the left half: left = mid + 1. If it is bigger, drop the right half: right = mid - 1. The + 1 and - 1 are there because mid has already been checked.
⚡ <= and Math.floor
Meaning: Use while (left <= right), not <, so the last number left (when left equals right) still gets checked. Math.floor rounds mid down, because an index has to be a whole number: arr[3.5] is undefined.
⚡ The rule: sorted data
Guess first: what does binarySearch([5, 1, 9, 3, 7], 1) return?
-1, even though 1 is at index 1. This array isn't sorted, so binary search drops the wrong part. The result is quietly wrong, with no error.
Meaning: When the middle item is smaller than the target, binary search drops the left half, because in sorted data every number to the left of the middle is even smaller. On shuffled data, the dropped part can hold the target.
⚡ Why it's fast: O(log n)
Guess first: a friend thinks of a number from 1 to 100 and only says "higher", "lower" or "right". If you always guess the middle number, how many guesses do you need at most?
7 guesses. Each guess throws away half: 100 numbers become 50, 25, 12, 6, 3, then 1.
Meaning: Every step throws away half of what's left, so binary search is written O(log n): double the data, and it takes just one more step. 1,000 items take about 10 steps, 1 million about 20.