beginnerO(log n)searching

Binary Search

Published August 15, 2026

Understanding Binary Search

Binary search is one of the most fundamental algorithms in computer science. It efficiently finds a target value within a sorted array by repeatedly dividing the search interval in half.

How It Works

  1. Start with the entire sorted array
  2. Find the middle element
  3. If the middle element equals the target, we're done
  4. If the target is less than the middle, search the left half
  5. If the target is greater than the middle, search the right half
  6. Repeat until the target is found or the range is empty

Code Snippets

def binary_search(sorted_array: list[int], target: int) -> int:
    """Find target in a sorted array. Returns index or -1 if not found."""
    left_bound = 0
    right_bound = len(sorted_array) - 1

    while left_bound <= right_bound:
        middle_index = left_bound + (right_bound - left_bound) // 2
        middle_value = sorted_array[middle_index]

        if middle_value == target:
            return middle_index
        elif middle_value < target:
            left_bound = middle_index + 1  # target is in the right half
        else:
            right_bound = middle_index - 1  # target is in the left half

    return -1  # target not found

Lower Bound Variation

Find the first position where a value could be inserted to maintain sorted order:

def lower_bound(sorted_array: list[int], target: int) -> int:
    """Find the leftmost position where target could be inserted."""
    left_bound = 0
    right_bound = len(sorted_array)

    while left_bound < right_bound:
        middle_index = left_bound + (right_bound - left_bound) // 2

        if sorted_array[middle_index] < target:
            left_bound = middle_index + 1
        else:
            right_bound = middle_index

    return left_bound

Time Complexity

Binary search runs in O(log n) time because each comparison eliminates half of the remaining elements.

For an array of 1,000,000 elements, binary search needs at most ~20 comparisons.

When to Use

  • The array must be sorted
  • You need to find a specific element
  • You want better than O(n) performance

Common Pitfalls

  • Forgetting the array needs to be sorted first
  • Integer overflow when calculating middle = (left + right) / 2 — use middle = left + (right - left) // 2 instead
  • Off-by-one errors: use left_bound <= right_bound for finding exact values, left_bound < right_bound for bounds