Binary Search

Beginner
Search
Requires sorted array

Binary Search eliminates half the remaining elements with every comparison by always checking the middle of the current search window. O(log n) — dramatically faster than Linear Search on large sorted arrays.

Auto-sorted: The array below is automatically sorted in ascending order. Binary Search only works correctly on sorted data.

Search Target

Quick examples:

↑ Set a target value above to begin searching the array

Loading controls...
Loading visualization...
Time: O(log n)
Space: O(1)

Legend

Mid (M)
Current middle element being compared
Found!
Target value located here
Active Search Window
Elements still in [Low … High] range
Eliminated
Faded — half discarded this step
Not Found
Search space fully exhausted
— — — target: N
Dashed line marks target height
Pointer labels on bars:
LLow — left boundary
MMid — currently comparing
HHigh — right boundary
Found position
Reading the chart:
  • • Bar height = element value
  • • Faded bars = eliminated half
  • • Dashed line = target level
  • • L, M, H labels show pointers

Inspector

No active frame to inspect

Reference implementation of Binary Search. Select a language tab to view and copy the code.

def binary_search(arr: list[int], target: int) -> int:
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = left + (right - left) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

Python — Code Walkthrough

  1. Tuple unpacking for bounds

    left, right = 0, len(arr) - 1

    Python multiple assignment initialises both bounds in one statement. right starts at the last valid index.

  2. Floor division // for mid

    mid = left + (right - left) // 2

    Python's // operator always floors (towards negative infinity), giving the lower-middle index for an even-length window. The subtraction form avoids overflow — though Python integers don't overflow, it is a good habit.

  3. elif chain — three outcomes

    if arr[mid] == target ... elif arr[mid] < target ... else

    Python elif is cleaner than nested ifs. The three branches cover: found (return mid), target is right of mid (move left forward), target is left of mid (move right back).

  4. Return -1 after the loop

    return -1

    The while loop exits when left > right, meaning the search window is empty. Returning -1 signals that target was not found.