Algorithms

Binary Search

A sorted array and a target. Watch low, high, and mid pointers close in on the answer in logarithmic time.

4 minLevel 1/3The interactive stage stays ad-free.
Target43Range0–23Mid index11Comparisons1
3
7
11
15
19
23
27
31
35
39
43
47
51
55
59
63
67
71
75
79
83
87
91
95

The cyan range is still possible. The amber cell is the midpoint being compared. Each comparison removes roughly half of the remaining values, so the search needs only about log₂(24) ≈ 5 steps.

What you are seeing

1

The array is sorted, so one comparison can eliminate half of the remaining elements.

2

The midpoint splits the current range into a left half and a right half.

3

If the middle value is too small, move low up; if it is too large, move high down.

Why it matters

Binary search is one of the highest-leverage algorithms you can learn: databases, version control, and search indexes all use the same halving idea.

Complexity & details

Time: O(log n) comparisons. Space: O(1) iterative.

Frequently asked questions

Why does the array need to be sorted?+

The halving step depends on knowing which side of the midpoint can contain the target. Without order, you cannot discard half safely.

What is an off-by-one error in binary search?+

It usually comes from updating low or high incorrectly, causing an infinite loop or skipping the answer. Use low = mid + 1 and high = mid - 1 with a consistent range convention.