An efficient divide-and-conquer search algorithm for sorted arrays
Binary search is an efficient search algorithm that finds the position of a target value within a sorted array by repeatedly dividing the search interval in half.
Binary search works by comparing the target value to the middle element of the array. If they match, the position is returned. If the target is less than the middle element, the search continues in the lower half. If greater, it continues in the upper half. This process repeats until the value is found or the search space is empty.
Best case: O(1) - Element is at the middle position
Average case: O(log n) - Element requires multiple divisions
Worst case: O(log n) - Element is at an end or not present
The algorithm divides the search space in half with each iteration, resulting in logarithmic time complexity. This makes it extremely efficient for large datasets.For example:
Array of 1,000 elements: ~10 comparisons maximum
Array of 1,000,000 elements: ~20 comparisons maximum
Space complexity
Iterative: O(1) - Constant space
Recursive: O(log n) - Call stack depth
The iterative version uses only a few variables. The recursive version uses stack space proportional to the number of recursive calls.
Integer overflow: When calculating middle index, (start + end) / 2 can overflow for very large arrays. Use start + Math.floor((end - start) / 2) instead.
Boundary conditions: Pay careful attention to <= vs < in loop conditions and middle + 1 vs middle - 1 when updating bounds.