Binary Search
Binary search finds a target value in a sorted array by cutting the search range in half again and again.
At a Glance
It searches by splitting the search range into two parts. It is much faster than a full scan that checks every element from start to finish.
It is like looking up a word in a dictionary. When you look for a word starting with "T," you do not flip from the first page. You open somewhere around the middle, and if the word you want is further back, you look only at the back half; if it is further forward, you look only at the front half.
| Method | Time complexity |
|---|---|
| Full scan | O(N) |
| Binary search | O(log N) |
However, binary search can only be used if the array is already sorted. The judgment "if it is larger than the middle value, it is on the right" is only valid when the array is sorted.
How It Works
- First, sort the array. (Skip this if it is already sorted.)
- Use the left end of the range
leftand the right endrightto determine the middle positionmid. - Compare the value at position
midwith the value you are looking for. - If the target is larger than the value at
mid, shrink the range withleft = mid + 1; if it is smaller, useright = mid - 1. - If they are equal, you found it; if
left > right(the range is empty), the value is not there.
Example: finding 11 in [1, 3, 5, 7, 9, 11, 13]
| Step | left | right | mid | arr[mid] | Explanation |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 7 | 7 < 11 → go to the right half (left = 4) |
| 2 | 4 | 6 | 5 | 11 | Found! Return index 5 |
Example: finding 4 in the same array (a value that is not there)
| Step | left | right | mid | arr[mid] | Explanation |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 7 | 7 > 4 → go to the left half (right = 2) |
| 2 | 0 | 2 | 1 | 3 | 3 < 4 → go to the right half (left = 2) |
| 3 | 2 | 2 | 2 | 5 | 5 > 4 → go to the left half (right = 1) |
| 4 | 2 | 1 | - | - | left > right → the range is empty, so the value is not there |
There are 7 elements, but at most 3 comparisons are needed to reach a conclusion.
The figure below shows a search for 7 in a sorted array of 17 elements. It compares with the middle value 14 and moves to the left half, compares with the middle value 6 and moves right, then compares with 8 and moves left, finding 7 in four steps.

Image source: Wikimedia Commons (CC BY-SA 4.0, AlwaysAngry)
Python Code
def binary_search(arr, target):
"""Binary search that finds the index of target in the sorted arr"""
# 1. Both ends of the search range
left, right = 0, len(arr) - 1
# 2. Repeat while the range is not empty
while left <= right:
mid = (left + right) // 2 # 3. Middle position
if arr[mid] == target: # 4. Found it
return mid
elif arr[mid] < target: # 5. Target is larger → right half
left = mid + 1
else: # 6. Target is smaller → left half
right = mid - 1
# 7. The range is empty and it was not found
raise ValueError("Target does not exist")
arr = [9, 1, 13, 5, 3, 11, 7]
arr.sort() # Always sort before binary search
print(arr) # Output: [1, 3, 5, 7, 9, 11, 13]
print(binary_search(arr, 11)) # Output: 5leftis the first index of the range andrightis the last index.- While
left <= right, there are still cells left to check. - Compute the middle index.
//is division that keeps only the quotient. - If the middle value is the target, return its index immediately.
- If the middle value is smaller, the answer is on the right, so move the left end to
mid + 1. - If the middle value is larger, the answer is on the left, so move the right end to
mid - 1. - If the range becomes empty, the value is not in the array, so raise an error.
Things to watch out for:
- Sort only once, outside the function. If you sort inside the function every time, as the original source does, the returned index refers to the sorted array rather than the original array, and every call pays the O(N log N) sorting cost, which wipes out the benefit of binary search.
- In languages with limited integer sizes, such as Java and C,
(left + right) / 2can overflow, so it is often written asleft + (right - left) / 2. Python integers have no limit, so this is not a problem. - Python also has a standard module for binary search,
bisect.bisect.bisect_left(arr, x)tells you wherexwould go in O(log N).
Time and Space Complexity
| Case | Time complexity | Reason |
|---|---|---|
| Best | O(1) | The first middle value is the answer |
| Average | O(log N) | Each comparison cuts the range in half |
| Worst | O(log N) | Even halving until the range is 1 cell takes only about log₂N steps |
- Space complexity: O(1) extra memory (just a few variables:
left,right,mid) - If the array is not sorted, the O(N log N) sorting cost comes first. That is why it is most effective when you sort once and search many times.
Even with 1 million elements, it finds the value in about 20 steps (2²⁰ ≈ 1 million). If complexity notation is unfamiliar, it helps to read the time complexity article first.
Where It Is Used
- Checking whether a value exists in a sorted list, and at which position
- Finding where a value should go (
bisect), and inserting while keeping the list sorted - Problems that find "the smallest/largest value that satisfies a condition" (halving the range of possible answers, often called "parametric search")
- Computing the Longest Increasing Subsequence (LIS) in O(N log N)
Summary
| Concept | Plain-language summary |
|---|---|
| Binary search | Open to the middle like a dictionary and throw away half each time |
| Precondition | The array must be sorted |
| Speed | Finds a value among 1 million in about 20 comparisons (O(log N)) |
