Web Analytics

📖 Binary Search

Beginner to Intermediate ~15 min read

Looking for a word in a dictionary with 100,000 words? Do you start from page 1 and check every word? No! You open the middle, see if your word comes before or after, then repeat. Each step cuts the search space in half. That's Binary Search - the most elegant algorithm in computer science!

The Dictionary Lookup

Imagine searching for "algorithm" in a dictionary:

The Smart Strategy

  1. Open middle: See "mango" - your word comes BEFORE
  2. Throw away second half: Only search first half
  3. Open middle of first half: See "dog" - your word comes BEFORE again
  4. Repeat: Keep halving until you find it!

Key insight: Each step eliminates HALF the remaining words!

The Power of Halving

Why O(log n) is Amazing

With 1 million items, how many steps? Just 20!

  • 1,000,000 → 500,000 → 250,000 → 125,000 → ...
  • Each step cuts the problem in half
  • After 20 steps: down to 1 item!

That's O(log n) - logarithmic time!

See It in Action

Watch how Binary Search eliminates half the array with each comparison:

Understanding the Process

  • L (Left): Start of search range
  • R (Right): End of search range
  • M (Mid): Middle element to compare
  • Blue boxes: Current search range
  • Faded boxes: Eliminated from search
  • Green box: Target found!

The Requirement: Sorted Array

⚠️ Binary Search ONLY Works on Sorted Arrays

Why? We need to know if the target is in the left or right half!

  • ✅ Sorted: [1, 3, 5, 7, 9] - Binary Search works!
  • ❌ Random: [5, 1, 9, 3, 7] - Binary Search fails!

If your array isn't sorted, either sort it first (O(n log n)) or use Linear Search (O(n)).

The Code

Output
Click Run to execute your code
Iterative vs Recursive: Both have O(log n) time, but iterative uses O(1) space while recursive uses O(log n) space for the call stack. Iterative is recommended for production!

Quick Quiz

  • Why is Binary Search O(log n) and not O(n)?
    Show answer Each comparison eliminates HALF the remaining elements. How many times can you halve n until you reach 1? log₂(n) times! For 1 million elements, that's only 20 comparisons. Linear search would need up to 1 million!
  • What's the common mistake: mid = (left + right) / 2?
    Show answer Integer overflow! If left and right are large, their sum might overflow. Safe version: mid = left + (right - left) / 2. This avoids overflow while giving the same result.

Why O(log n)?

Let's understand logarithmic time complexity:

Array Size Linear Search Binary Search Speedup
10 10 4 2.5x
100 100 7 14x
1,000 1,000 10 100x
1,000,000 1,000,000 20 50,000x
1,000,000,000 1,000,000,000 30 33,000,000x

✅ The Magic of Logarithms

Doubling the input only adds ONE more step!

  • 1,000 elements: 10 steps
  • 2,000 elements: 11 steps (just +1!)
  • 1,000,000 elements: 20 steps
  • 2,000,000 elements: 21 steps (just +1!)

This is why Binary Search scales beautifully to massive datasets!

Common Pitfalls

❌ Pitfall 1: Integer Overflow

Wrong: mid = (left + right) / 2

Right: mid = left + (right - left) / 2

If left and right are large (e.g., near 2 billion), their sum can overflow!

❌ Pitfall 2: Infinite Loop

Wrong: right = mid (can loop forever)

Right: right = mid - 1

Always move the pointer PAST the mid to avoid infinite loops!

❌ Pitfall 3: Off-by-One Error

Wrong: while left < right

Right: while left <= right

Use <= to handle the case when left and right point to the same element!

Real-World Applications

Where Binary Search is Used

  • Databases: B-tree indexes use binary search variant
  • Java: Arrays.binarySearch()
  • Python: bisect module
  • C++: std::binary_search()
  • Git: git bisect finds bugs in commit history
  • Games: Pathfinding optimizations
  • Libraries: Finding books, contacts, any sorted data

Binary Search vs Linear Search

Feature Linear Search Binary Search
Time Complexity O(n) O(log n) ✓
Space Complexity O(1) ✓ O(1) iterative ✓
Requirement Any array ✓ Sorted array only
Best Case O(1) - first element O(1) - middle element
Worst Case O(n) O(log n) ✓
Use When Small or unsorted Large and sorted ✓

The Trade-off

Binary Search is faster BUT requires sorted data.

  • If data is already sorted: Use Binary Search!
  • If sorting cost < search savings: Sort then Binary Search
  • If data is unsorted and small: Linear Search is fine

💡 Key Takeaway

Binary Search is the most important searching algorithm:

  • ✅ O(log n) - logarithmic time complexity
  • ✅ 50,000x faster than linear for 1M elements
  • ✅ Foundation for many interview problems
  • ✅ Used everywhere in production code
  • ⚠️ Requires sorted array
  • ⚠️ Watch for overflow and off-by-one errors

Master Binary Search - it's essential for every programmer!

Summary

The 3-Point Binary Search Guide

  1. Strategy: Divide and conquer - eliminate half each step
  2. Complexity: O(log n) - 20 steps for 1 million items!
  3. Requirement: Array must be sorted

Interview tip: Binary Search is a MUST KNOW. Practice iterative and recursive versions. Know the variants (first/last occurrence, rotated array). Mention O(log n) and the sorted requirement!

What's Next?

You've mastered Binary Search! Next: Linear Search - the baseline searching algorithm for comparison.

Practice: Implement Binary Search from scratch. Try the variants: find first occurrence, find last occurrence, search in rotated sorted array!