π« 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)