Binary Search: Search Space Elimination, Lower Bound & Upper Bound
Binary Search: Search Space Elimination, Lower Bound & Upper Bound
Binary Search is the cornerstone divide-and-conquer searching algorithm. By repeatedly halving the search space of a sorted sequence, binary search locates elements in $O(\log n)$ logarithmic time, searching through 4 billion items in just 32 comparisons!
1. Real-World Analogy: The Guessing Game (1 to 100)
Suppose someone asks you to guess a hidden secret number between 1 and 100:
- If you guess 1, 2, 3, 4, 5... you might need 100 guesses (Linear Search).
- Instead, you guess 50! The host says: "Too low!"
- Instantly, numbers 1 through 50 are eliminated. The search space shrinks from 100 to 50 items in a single guess.
- Next, you guess 75. The host says: "Too high!"
- Numbers 75 through 100 are eliminated. In just 7 guesses, you can find any number from 1 to 100 ($2^7 = 128$).
2. The Core Binary Search Algorithm
3. Preventing the Integer Overflow Bug
In languages like C++, Java, and Go, writing mid = (low + high) / 2 can cause a catastrophic 32-bit integer overflow if low + high > 2,147,483,647, wrapping around into a negative number.
Always calculate mid using the mathematically equivalent overflow-safe formula: $$\text{mid} = \text{low} + \left\lfloor\frac{\text{high} - \text{low}}{2}\right\rfloor$$
4. Multi-Language Implementations: Classic & Lower Bound
Python 3:
Modern JavaScript / TypeScript:
5. Trace Table: Searching for 70 in [10, 20, 30, 40, 50, 60, 70, 80]
| Step | low | high | mid | nums[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 40 | $40 < 70$ | low = mid + 1 = 4 |
| 2 | 4 | 7 | 5 | 60 | $60 < 70$ | low = mid + 1 = 6 |
| 3 | 6 | 7 | 6 | 70 | $70 == 70$ | Target Found at Index 6! |
Multiple Choice Questions
mid = low + (high - low) // 2 preferred over mid = (low + high) // 2?Binary Search on Answer Space: Allocation & Feasibility Checks
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.