Binary search is an efficient algorithm for finding an element in a sorted array. It works by repeatedly dividing the search interval in half.
Enter a number and click 'Search' or 'New Array' to begin.
Binary search follows these steps:
O(log n) - With each step, we eliminate half of the remaining elements.
O(1) - Iterative approach uses constant extra space.
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
let guess = arr[mid];
if (guess === target) {
return mid; // Found the item
}
if (guess > target) {
high = mid - 1; // Target is in the left half
} else {
low = mid + 1; // Target is in the right half
}
}
return -1; // Item not found
}