Binary Search Visualization & Animation

Eliminates half the search space each step on a sorted array; O(log n).

## What is it? Binary Search is an efficient search algorithm that works on **sorted** arrays. It repeatedly divides the search space in half by comparing the target with the middle element, eliminating half the remaining candidates each step. ## How it works - Set `low = 0`, `high = n-1` - Compute `mid = (low + high) / 2` - If `arr[mid] == target` → found, return `mid` - If `arr[mid] < target` → target is in the right half; set `low = mid + 1` - If `arr[mid] > target` → target is in the left half; set `high = mid - 1` - Repeat until `low > high` (not found) ## When to use - Searching in any sorted collection - Finding insertion points, lower/upper bounds - Solving optimization problems where the answer space is monotone ("binary search on the answer") ## Key Points - Requires the array to be sorted — cannot be used on unsorted data - O(log n) — eliminates half the search space each iteration - Off-by-one errors are common; be careful with `mid` calculation and boundary updates - Prefer `mid = low + (high - low) / 2` to avoid integer overflow

Category: algorithms

Difficulty: beginner

Time Complexity: O(log n)

Space Complexity: O(1)

Binary Search

beginner

Eliminates half the search space each step on a sorted array; O(log n).

10
[0]
20
[1]
30
[2]
40
[3]
50
[4]
60
[5]
70
[6]
80
[7]
Left / mid / right pointers
Eliminated half
Target found
Not found
Starting binary search. Looking for 50 in sorted array: [10, 20, 30, 40, 50, 60, 70, 80]