All algorithms
Searching

Binary Search

Halve the search space every step — find a value in a sorted array in O(log n).

TimeO(log n)SpaceO(1)CategorySearching

Binary Search works on a sorted array by repeatedly halving the range: compare the target to the middle element, then discard the half that cannot contain it. Each step throws away half the remaining elements, so the whole search takes only about log₂(n) comparisons.

The classic bugs live in the boundaries — `low <= high` vs `low < high`, and how `mid` is computed. Watching the `low`, `mid`, and `high` pointers move on the array is the fastest way to understand (and debug) those boundaries.

AlgoLens draws the array with the three pointers stepping through it, so you see exactly which half survives each comparison.

The code

binary_search.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {1, 3, 4, 6, 7, 9, 11, 15};
    int target;
    cin >> target;

    int left = 0, right = a.size() - 1, found = -1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (a[mid] == target) {
            found = mid;
            break;
        }
        if (a[mid] < target) left = mid + 1;
        else right = mid - 1;
    }

    cout << found << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Binary Search

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going