Binary Search Visualizer
SlowFast
715
(10)Mid Point
Boundaries
Target Value
Found
Out of Range
Operation Logs
No operations yet
Algorithm Info
Time Complexity: O(log n) - divides search space in half each iteration
Space Complexity: O(1) - uses constant extra space
Best Case: O(1) - target is the middle element
Worst Case: O(log n) - target is at the ends or not found
Prerequisite: Array must be sorted in ascending order
How it works: Compares target with middle element, then searches either left or right half, eliminating half the elements each time.
When to use: Large sorted datasets where O(log n) performance is crucial.
Implementation
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
// Find middle point
const mid = Math.floor((left + right) / 2);
// Check if target is at mid
if (arr[mid] === target) {
return mid; // Found!
}
// If target is greater, ignore left half
if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore right half
else {
right = mid - 1;
}
}
return -1; // Not found
}