What is Binary Search?
Binary Search only works because the list is already sorted, and it takes full advantage of that: check the middle element, and if the target is smaller, throw away the entire upper half; if it's larger, throw away the entire lower half. Repeating that halving keeps shrinking the search space until you land on the value.
How Does It Work?
Imagine you have a sorted list of numbers: [1, 3, 5, 7, 9, 11, 13] and you want to find the number 7.
- Compare 7 with the middle element (7). It matches! Return the position.
- If searching for 5:
- First middle is 7 (too high)
- Search left half: [1, 3, 5]
- New middle is 3 (too low)
- Search right portion: [5]
- Found at position 2
If the number is not in the list (e.g., searching for 8), the search ends when the subarray becomes empty.
Algorithm Steps
- Start with the entire sorted array
- Compare the target with the middle element:
- If equal, return the position
- If target is smaller, search the left half
- If target is larger, search the right half
- Repeat until the element is found or the subarray is empty
- If not found, return "Not Found"
Time Complexity
- Best Case: Target is the middle element → O(1).
- Worst Case: Element not present → O(log n) (halves search space each step).
Time Complexity Analysis
Binary Search is extremely fast for large datasets but requires the list to be sorted beforehand. It's much more efficient than Linear Search for sorted data.