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)