Binary Search
Searchingeasy#7Divide sorted array in half repeatedly to find target
Ready
Step 1 of 0
Speed
Input Data
Comma-separated numbers (0-999). Min 2 values.
Algorithm Code
1function binarySearch(arr, target) {2 let left = 0, right = arr.length - 1;3 while (left <= right) {4 const mid = Math.floor((left + right) / 2);5 if (arr[mid] === target) return mid;6 if (arr[mid] < target) left = mid + 1;7 else right = mid - 1;8 }9 return -1;10}
Best
O(1)
Average
O(log n)
Worst
O(log n)
Space
O(1)
About Binary Search
Binary Search efficiently finds a target value in a sorted array by repeatedly dividing the search interval in half. If the target is less than the middle element, search the left half; otherwise search the right half. One of the most fundamental algorithms in computer science.
Time Complexity: Best: O(1), Average: O(log n), Worst: O(log n). Space: O(1).