Introduction
Binary Search is a powerful searching algorithm that works by repeatedly dividing the search space in half. The core idea is simple - at each step, we look at the middle element and eliminate half of the remaining search space that cannot possibly contain our target. This process continues until we either find the target or determine it doesn’t exist.
For example, when searching for a number in a sorted array, we compare our target with the middle element. If the target is smaller, we can safely discard the entire right half since all elements there would be too large. Similarly, if the target is larger, we discard the left half. By eliminating half the possibilities in each step, we reduce the search time from to .
The algorithm requires the data to be sorted, which may take time initially. However, once sorted, all subsequent binary searches will be very efficient, especially for large datasets where the time complexity really shines compared to linear search.
Binary search isn’t limited to just finding specific values - it can also be used to find minimum or maximum values that satisfy certain conditions in a search space.
Implementation
Searching minimum
Searching maximum
Complexity
- Time complexity: for the search function
- Space complexity: