What is Binary Search?
Binary Search is one of the most powerful techniques in computer science. It reduces search time from O(n) to O(log n) by eliminating half the search space in each step.
Real-World Analogy: The Dictionary
Imagine searching for "inheritance" in a physical dictionary. You wouldn't flip page by page from the start. Instead:
- •Open somewhere in the middle, land on "M"
- •"Inheritance" comes before "M" → search left half
- •Open the left half, land on "F"
- •"Inheritance" comes after "F" → search right half
- •Continue until you find "I" section
Each step eliminates half the pages. This is binary search!
Visual Comparison:
Why O(log n)?
- •Each step cuts the search space in HALF
- •n → n/2 → n/4 → n/8 → ... → 1
- •Takes log₂(n) steps to reduce n elements to 1
- •log₂(1,000,000) ≈ 20 steps for a million elements!