Binary search is a search algorithm that operates on a sorted array or list. It uses the divide-and-conquer approach to repeatedly divide the search interval in half until the target value is found or determined to be not in the array.
Binary search requires the array to be sorted. With a time complexity of O(log n), it's much faster than linear search for large datasets.
Binary search starts with two pointers, low and high, to represent the bounds of the search interval. The middle index is calculated with (low+high)//2, and comparison is made against the middle element.
Binary search can be implemented both iteratively and recursively. The base case for the recursive implementation is low>high indicating that the target is not in the array.
The time complexity of binary search, whether iterative or recursive, is O(log n), which makes binary search suitable for large sorted datasets.
Practical considerations include ensuring the array is sorted and using the non-recursive approach to avoid overhead of recursive function calls.
Applications of binary search go beyond simply finding an element in an array. Some of the key applications include finding lower and upper bounds, searching in infinite lists, and solving optimization problems.
Finding the lower bound of a value in a sorted array is finding the index of the first element that is not less than the target value.
Binary search is a versatile algorithm with numerous applications beyond simply finding an element in an array.
Binary search is a widely used and efficient algorithm that is simple to implement and guarantees deterministic results when used correctly.