11
12
22
25
34
64
90
0
1
2
3
4
5
6
Starting Binary Search for target value 25 on sorted array.
Presets:
Size:
Timeline Progress:
0%Step 1 / 3
Comparisons
0
Swaps / Actions
0
Speed:
Shortcuts: Space Play • ←/→ Step • R Reset • M Sound • Z Focus
Implementation Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function binarySearch(arr: number[], target: number): number {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}Complexity Analysis
Best Case
O(1)
Average Case
O(log n)
Worst Case
O(log n)
Space
O(1)
Color Legend
Array Element
Comparing / Inspecting
Target Found
Binary Search works on sorted arrays by repeatedly comparing the target value to the middle element. If the target matches the middle element, its index is returned. If the target is smaller, search continues on the left half; if larger, on the right half. This halves the search space each step, achieving O(log n) time complexity.