The binary search algorithm is the fastest way to find an item in a sorted list, and one of the first algorithms every computer science student learns. It's also an interview favourite, because it's short to write but easy to get subtly wrong.
In this guide you'll see how binary search works step by step, why its time complexity is O(log n), working code in Python, Java and C++, and a memory trick so you never forget the rules.
Try it first: the guessing game
Before any theory, play this. You're about to watch binary search beat you at a game.
🎯 I'll guess your number in 7 tries
Think of a whole number from 1 to 100. Don't tell me. Just answer honestly.
Guess #1 · searching 1–100 (100 left)
Is it 50?
That's binary search. The computer never guessed randomly; it always picked the middle of what was left, so every answer cut the possibilities in half.
What is binary search?
Binary search is a searching algorithm that finds a target value in a sorted array by repeatedly dividing the search range in half. It compares the target with the middle element:
- If they're equal, you're done.
- If the target is bigger, it can only be in the right half, so ignore the left.
- If the target is smaller, it can only be in the left half, so ignore the right.
How binary search works, step by step
- Set two pointers:
lowat the first index andhighat the last. - While
low ≤ high, find the middle:mid = (low + high) / 2(rounded down). - If
arr[mid]equals the target, returnmid. - If
arr[mid]is smaller than the target, setlow = mid + 1. - Otherwise, set
high = mid - 1. - If
lowpasseshigh, the target isn't there: return-1.
👣 Step through binary search
Step 1/9: Looking for 41. The array is sorted, so we can use binary search. low = 0, high = 14.
Binary search code (Python, Java, C++)
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid # found: return the index
elif arr[mid] < target:
low = mid + 1 # target is in the right half
else:
high = mid - 1 # target is in the left half
return -1 # not found
nums = [3, 7, 11, 15, 19, 24, 28, 33, 41]
print(binary_search(nums, 24)) # 5
print(binary_search(nums, 50)) # -1Binary search time complexity
Every comparison halves the remaining items. Starting from n items, after k steps you have n / 2ᵏ left. You're done when that reaches 1, so k = log₂(n). That's why binary search is O(log n). (New to this notation? Read Big O notation explained.)
| Best case | O(1): the first middle element is the target |
| Average case | O(log n) |
| Worst case | O(log n): item is at an end or missing |
| Space (iterative) | O(1) |
| Space (recursive) | O(log n): one stack frame per halving |
To feel how fast that is: linear search through a billion sorted items could take a billion comparisons. Binary search needs about 30.
🧠 PATH memory card
Remember binary search for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
Looking up “mango” in a paper dictionary: you never read from page 1. You open the middle, see “L”, ignore everything before it, open the middle of what's left, and land on “M” in a few looks.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Sorted → Middle → Halve (if it's not Sorted, just Shake My Head)”
- Sorted→Only works on sorted data. Check this first!
- Middle→Always compare with the middle element
- Halve→Drop the half that can't hold the target, repeat
- SMH→Sorted, Middle, Halve: the 3 steps in order
- 10 for a thousand→About 10 steps for 1,000 items
- 20 for a million→About 20 steps for 1,000,000 items, so O(log n)
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Find 23 in[2, 5, 8, 12, 16, 23, 38, 56, 72, 91]: mid index 4 → 16 (too small, go right) → mid index 7 → 56 (too big, go left) → mid index 5 → 23 ✓. Three looks out of ten items. Write the low/mid/high values on paper once. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 8 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Linear search vs binary search
- Linear search: works on any list, checks items one by one, O(n).
- Binary search: needs sorted data, halves the range each step, O(log n).
- If you search an unsorted list only once, linear search is fine. If you search many times, sort once (see our sorting algorithms guide) and binary search after.
What to learn next
Binary search is the foundation for binary search trees and many “search on the answer” interview problems. Next, learn the two everyday data structures in stack vs queue.
Key takeaways
- Binary search only works on sorted data.
- Compare with the middle, throw away the half that can't contain the target, repeat.
- Time complexity is O(log n): about 20 steps for a million items.
- Use low ≤ high, and move pointers to mid + 1 or mid - 1 to avoid infinite loops.
- Remember it with “Sorted → Middle → Halve.”
Frequently asked questions
What is binary search in simple words?
Binary search finds an item in a sorted list by repeatedly checking the middle element and throwing away the half that cannot contain the target. Each step halves the search space, so it finds items very quickly.
What is the time complexity of binary search?
Binary search runs in O(log n) time in the average and worst case, and O(1) in the best case (when the middle element is the target). The iterative version uses O(1) extra space; the recursive version uses O(log n) space for the call stack.
Why does binary search need a sorted array?
Because it decides which half to throw away by comparing the target with the middle element. That decision is only correct if everything on the left is smaller and everything on the right is larger, which is true only when the data is sorted.
What is the difference between linear search and binary search?
Linear search checks items one by one and works on any list, taking O(n) time. Binary search needs sorted data but takes only O(log n) time: about 20 steps for a million items instead of up to a million.
Why do people write mid = low + (high - low) / 2?
In languages with fixed-size integers like Java and C++, (low + high) can overflow when both are very large. low + (high - low) / 2 gives the same middle without overflowing. Python integers don't overflow, so (low + high) // 2 is fine there.
🧠 Quick check: binary search
1. What must be true about the data before you use binary search?
2. What is the worst-case time complexity of binary search?
3. Roughly how many steps does binary search need for 1,000,000 sorted items?
4. arr[mid] is smaller than the target. What should you do?