Skip to content

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.

MethodTime complexity
Full scanO(N)
Binary searchO(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 ​

  1. First, sort the array. (Skip this if it is already sorted.)
  2. Use the left end of the range left and the right end right to determine the middle position mid.
  3. Compare the value at position mid with the value you are looking for.
  4. If the target is larger than the value at mid, shrink the range with left = mid + 1; if it is smaller, use right = mid - 1.
  5. 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]

Stepleftrightmidarr[mid]Explanation
106377 < 11 → go to the right half (left = 4)
246511Found! Return index 5

Example: finding 4 in the same array (a value that is not there)

Stepleftrightmidarr[mid]Explanation
106377 > 4 → go to the left half (right = 2)
202133 < 4 → go to the right half (left = 2)
322255 > 4 → go to the left half (right = 1)
421--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.

Finding 7 in a sorted array by comparing with the middle value and halving the range each time

Image source: Wikimedia Commons (CC BY-SA 4.0, AlwaysAngry)

Python Code ​

python
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: 5
  1. left is the first index of the range and right is the last index.
  2. While left <= right, there are still cells left to check.
  3. Compute the middle index. // is division that keeps only the quotient.
  4. If the middle value is the target, return its index immediately.
  5. If the middle value is smaller, the answer is on the right, so move the left end to mid + 1.
  6. If the middle value is larger, the answer is on the left, so move the right end to mid - 1.
  7. 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) / 2 can overflow, so it is often written as left + (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 where x would go in O(log N).

Time and Space Complexity ​

CaseTime complexityReason
BestO(1)The first middle value is the answer
AverageO(log N)Each comparison cuts the range in half
WorstO(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 ​

ConceptPlain-language summary
Binary searchOpen to the middle like a dictionary and throw away half each time
PreconditionThe array must be sorted
SpeedFinds a value among 1 million in about 20 comparisons (O(log N))