Skip to main content

Command Palette

Search for a command to run...

πŸ“– Binary Search Explained Like You're 5

Published
β€’2 min read
S

Building AI systems and writing about how they actually work. Master of AI @ University of Technology Sydney. Previously B.Tech CS with focus on IoT. I believe the best way to learn is to explain. That's why I'm documenting tech concepts with simple analogies (@sreekarreddy.com). AWS Certified β€’ Azure AI Certified β€’ Neo4j Professional β€’ Google Data Analytics When not coding: exploring Sydney, working on side projects, and teaching tech to anyone who'll listen.

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

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

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.

More from this blog

esreekarreddy

132 posts