๐ง The Magic of Smart Searching
โจ A Tale of Sorted Boxes & Smart Moves
๐ฆ A Tale of Two Halves: The Smart Snack Box ๐ซ
You’re back in your room and spot your snack stash โ but this time
itโs super organized.
All your chocolates are sorted in alphabetical order:
[5-Star, Dairy Milk, KitKat, Munch, Perk]
Now, you want to grab your fav โ Munch.
But wait! ๐ค Instead of checking each one (like in linear search),
youโve got a smarter plan this time!
๐ง What is Binary Search?
Binary Search is like being a smart detective in a sorted list ๐ต๏ธโโ๏ธ.
Rather than checking one-by-one, you go straight to the middle!
You divide and conquer!
๐ฅ Cut the list in half
๐ Check the middle item
๐ Decide: Go left? Or go right?
Repeat till you find it (or not)!
๐ฏ Letโs Do a Dry Run:
Snack box = [5-Star, Dairy Milk, KitKat, Munch, Perk]
You’re searching for Munch ๐ซ
Letโs turn the story into steps:
โ What if itโs not there?
Snack box: [5-Star, Dairy Milk, KitKat, Munch, Perk]
You search for Snickers ๐ซ (not in list)
You do the same process:
Middle = KitKat โ not Snickers
Move right or left โ check โ still not there โ
๐ Eventually, you return -1 = Not Found.
๐ Steps to Remember:
Check if the array is sorted โ
Set two pointers โ low and high
While low <= high:
Find mid = (low + high)/2
Is it the target? โ ๐ฏ Return index!
If target < mid โ Move high = mid - 1
If target > mid โ Move low = mid + 1
If not found โ return -1 โ
๐งโ๐ป Code Time! (C++)
int binarySearch(vector& arr, string target) {
int low = 0, high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1; // Not Found
}
๐ก Quick Recap:
โ
Binary Search works only on sorted arrays
๐ Cut the search space in half every time
โก Time Complexity: O(log n)
๐ Way faster than Linear Search!
๐ช Real-World Analogy:
Imagine finding a name in a phone book ๐
Do you start from page 1?
Nope! You flip to the middle ๐ โ Then go left or right!
Thatโs Binary Search ๐ก
๐ฌ Wrapping Up
Binary Search is like Sherlock Holmes ๐ต๏ธโโ๏ธ โ it doesnโt check everything, it thinks, splits, and finds smartly!
So next time youโre searching something in a sorted list โ
Don't be slowโฆ go Binary! ๐ง โก
