Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Visualizer › Searching

Binary Search

On a sorted array, compares the target with the middle element and throws away the half that cannot contain it — halving the search space every step.

How it works

Complexity

Code (Python)

def binary_search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Practise: Binary Search problems