๐ซ A Chocolate Hunt Story
Imagine you're hungry (like really hungry ๐) and craving your favorite chocolate...
You open your snack box, and hereโs what you see:[KitKat, Dairy Milk, Munch, Perk, 5-Star]
Now, you donโt know where Dairy Milk is, so what do you do?
๐ Start checking one by one!
KitKat? โ โ Nope
Dairy Milk? โ โ
Yesss! Found it
That's exactly what Linear Search does in coding too!
๐ง What is Linear Search?
Linear Search is like going through each item one-by-one until you find the one you want.
No shortcuts. No tricks. Just pure checking โ start to end! ๐ถโโ๏ธ
๐กReal Example :
Let's say you have:
arr = [10, 25, 30, 45, 50]
target = 30
We want to find the number 30.
Letโs dry run this:
๐ข Result: Found at index 2.
โ What if itโs not there?
arr = [10, 25, 30, 45, 50]
target = 100
We check allโฆ and nope! Itโs not there
๐ In that case, we return -1 (means "Not Found").
๐ Simple Steps to Remember:
- Start from the first item
- Check: Is this the one?
- If yes โ ๐ return the index!
- If not โ move to next
- Repeat until: You find the item โ๏ธ Or reach the end โ (return -1)
๐งโ๐ปCode Time! (C++)
#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Found!
}
}
return -1; // Not found
}
int main() {
int chocoBox[] = {4, 8, 15, 23, 42};
int size = sizeof(chocoBox) / sizeof(chocoBox[0]);
int myFavorite = 23;
int result = linearSearch(chocoBox, size, myFavorite);
if (result != -1)
cout << "Yay! Found your favorite chocolate at position: " << result;
else
cout << "Oops! Your chocolate isn't in the box!" << endl;
return 0;
}
๐ฅ๏ธ Output :Yay! Found your favorite chocolate at position: 3
๐ฌ Wrapping Up
Linear Search = The simplest way to find something โ one step at a time.
No rocket science. Just like finding your Dairy Milk ๐ซ in a snack box!
Want more fun DSA stuff like this daily?
โจ Follow me โ Iโm Khushi, a fellow learner sharing daily bite-sized DSA logic, patterns & stories ๐
Letโs learn & grow together ๐
Top comments (0)