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:
- Open to middle β "K" (too early)
- Go to middle of second half β "R" (too late)
- Go to middle between K and R β "N" (close!)
- 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.
Top comments (0)