In the last lesson, Linear Search checked values one by one. On a million values, that can mean a million checks.
Binary Search does the same job in at most 20. You had a first look at it in the Big-O lesson. Now we'll understand it properly: how it works, why it is so fast, and the small mistakes that break it.
It has one condition: the array must be sorted. This is one of the biggest rewards of everything you learned in the Sorting section.
By the end of this lesson, you will understand:
- How Binary Search halves the search area at every step
- How to trace it by hand, for a value that is there and one that isn't
- How to write it in code, and use the built-in versions
- Why it is
O(log n) - The classic bugs, and how to avoid them
What Is Binary Search?
Binary Search keeps track of the part of the array where the target could still be, using two markers, low and high. At the start, that's the whole array.
Then it repeats:
- Find the middle position,
mid, betweenlowandhigh. - If
a[mid]is the target, you're done. Returnmid. - If
a[mid]is smaller than the target, the target can only be to its right (the array is sorted!). Movelowtomid + 1. - If
a[mid]is bigger than the target, the target can only be to its left. Movehightomid - 1. - If
lowpasseshigh, there's nothing left to search. Return-1.
Every check throws away half of what's left. That's what makes it so fast.
Watch it below. The blue band is the part still being searched, between low and high. Each check crosses out a whole half. Then try Missing value and Random.
The Guess-the-Number Analogy
A friend thinks of a number from 1 to 100. You guess, and they say "higher", "lower" or "correct".
1. Guess the Middle
You guess 50. They say "higher". In one guess, you've ruled out 1 to 50, half the numbers.
2. Guess the New Middle
Now it's between 51 and 100, so guess 75. "Lower." Now it's between 51 and 74.
3. Keep Halving
100 → 50 → 25 → 12 → 6 → 3 → 1. You will always get it in at most 7 guesses.
4. Why It Works
"Higher" and "lower" only make sense because numbers are in order. If your friend's numbers were shuffled, "higher" would tell you nothing.
Tracing It by Hand
Let's search the sorted array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] for 23. It has 10 values, at indexes 0 to 9.
low | high | mid | a[mid] | Decision |
|---|---|---|---|---|
| 0 | 9 | 4 | 16 | 16 < 23: go right, low = 5 |
| 5 | 9 | 7 | 56 | 56 > 23: go left, high = 6 |
| 5 | 6 | 5 | 23 | Found, return 5 |
Found at index 5, in just 3 checks. Linear Search would have needed 6.
When the Value Is Missing
Now search the same array for 40:
low | high | mid | a[mid] | Decision |
|---|---|---|---|---|
| 0 | 9 | 4 | 16 | 16 < 40: go right, low = 5 |
| 5 | 9 | 7 | 56 | 56 > 40: go left, high = 6 |
| 5 | 6 | 5 | 23 | 23 < 40: go right, low = 6 |
| 6 | 6 | 6 | 38 | 38 < 40: go right, low = 7 |
Now low is 7 and high is 6. low has passed high, so there's no value left that could be 40. Return -1, after 4 checks. Linear Search would have checked all 10.
Binary Search in Code
public class Main {
static int binarySearch(int[] a, int target) {
int low = 0;
int high = a.length - 1;
while (low <= high) { // something is left to search
int mid = low + (high - low) / 2; // the middle, without overflow
if (a[mid] == target) {
return mid; // found it
}
if (a[mid] < target) {
low = mid + 1; // the target can only be on the right
} else {
high = mid - 1; // the target can only be on the left
}
}
return -1; // nothing left: not there
}
public static void main(String[] args) {
int[] marks = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
System.out.println(binarySearch(marks, 23)); // 5
System.out.println(binarySearch(marks, 40)); // -1
}
}Let's connect the code to the trace:
lowandhighare the two ends of the blue band. Every row of the trace table is one trip round the loop.- The loop runs while
low <= high. Whenlow == high, one value is still left, and it must be checked too. low = mid + 1andhigh = mid - 1skipmiditself, because it has already been checked.- Java and C write
low + (high - low) / 2so thatlow + highcan never overflow on a huge array. You saw why in the Big-O lesson.
Built-in Versions
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] marks = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
System.out.println(Arrays.binarySearch(marks, 23)); // 5
System.out.println(Arrays.binarySearch(marks, 40)); // -8 (negative: not found)
}
}A few things to notice:
- Java's
Arrays.binarySearchreturns a negative number when the value is missing (-8here). Any negative result means "not found". - Python's
bisect_leftreturns where the value is, or would be inserted, so you must check that the value at that position really is your target. - C's
bsearchreturns a pointer to the value, orNULLif it is missing. - JavaScript's
indexOfworks, but it is a Linear Search: it doesn't know your array is sorted.
How Fast Is Binary Search?
Every check halves what's left. So the question is: how many times can you halve n before only one value is left? That number is log₂ n, which is why Binary Search is O(log n).
| Values (n) | Linear Search, worst case | Binary Search, worst case |
|---|---|---|
| 10 | 10 checks | 4 checks |
| 1,000 | 1,000 checks | 10 checks |
| 10 lakh (1,000,000) | 10 lakh checks | 20 checks |
| 100 crore (1,000,000,000) | 100 crore checks | 30 checks |
Multiplying the data by 1,000 adds only about 10 checks. That is the power of O(log n).
| Case | Time | Why |
|---|---|---|
| Best | O(1) | The target is exactly in the middle |
| Average | O(log n) | Halving until it is found |
| Worst | O(log n) | Halving until nothing is left |
| Extra memory | O(1) | Just low, high and mid |
Is Sorting First Worth It?
Sorting costs O(n log n), more than one O(n) Linear Search. So:
- Searching once? Just use Linear Search.
- Searching many times? Sort once, then every search is
O(log n). After enough searches, the sort pays for itself many times over.
Common Mistakes
1. Using It on Unsorted Data
Binary Search doesn't check that the data is sorted. It just gives wrong answers. Search [7, 3, 9, 1, 5, 8] for 3:
mid = 2,a[2] = 9. 9 is bigger than 3, so go left:high = 1.mid = 0,a[0] = 7. 7 is bigger than 3, so go left:high = -1.lowhas passedhigh: it returns-1, even though3is right there at index 1!
2. Writing low < high Instead of low <= high
With <, the loop stops while one value is still left unchecked. Search our sorted array for 91, the last value: low and high both reach 9, the loop stops, and 91 is reported missing.
3. Writing low = mid Instead of low = mid + 1
If low doesn't move past mid, the search area can stop shrinking. Searching for 91, you reach low = 8, high = 9, so mid = 8. 72 is smaller than 91, so low = mid = 8 again. The loop repeats forever.
4. Overflow When Finding the Middle
In Java and C, (low + high) / 2 can overflow when the array is huge. low + (high - low) / 2 gives the same middle safely.
When Should You Use Binary Search?
Good for:
- Sorted arrays, especially when you search them many times
- Huge amounts of data, where
O(n)is too slow
Not good for:
- Unsorted data that you only search once: use Linear Search
- Data that changes all the time, because keeping it sorted costs work too
The halving idea goes far beyond arrays. A paper dictionary works this way, git bisect uses it to find the commit that introduced a bug, and you'll see it again in Binary Search Trees.
That completes the Searching section! You can now find a value in any array: one by one with Linear Search, or by halving with Binary Search once the array is sorted.
Remember This
If you remember only one thing from this lesson, remember: Binary Search only works on sorted data. It checks the middle, throws away the half that can't hold the target, and repeats, so it takes O(log n) time: at most 20 checks for a million values.