DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

📖 Binary Search Explained Like You're 5

Finding a word in a dictionary

Day 41 of 149

👉 Full deep-dive with code examples


The Dictionary Game

Find "Mongoose" in a dictionary.

Bad way: Start at A, flip every page until M... 😴

Smart way:

  1. Open to middle → "K" (too early)
  2. Go to middle of second half → "R" (too late)
  3. Go to middle between K and R → "N" (close!)
  4. A bit earlier → "M" → Found Mongoose!

The Magic

Each step eliminates half the options!

N pages
→ N/2 pages (after step 1)
→ N/4 pages (after step 2)
→ N/8 pages (after step 3)
→ ... a lot fewer checks overall
Enter fullscreen mode Exit fullscreen mode

Instead of checking every page, you usually need far fewer checks.


The Catch

Works when the data is sorted.

Imagine a dictionary with random word order. How would you know which half to check?


In Code

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
Enter fullscreen mode Exit fullscreen mode

In One Sentence

Binary search finds items by repeatedly cutting the search area in half, assuming the data is sorted.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)