DEV Community

Khushi
Khushi

Posted on • Edited on

๐Ÿ”Linear Search Made Easy โ€“ Find Like a Detective!

๐Ÿซ 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;
}

Enter fullscreen mode Exit fullscreen mode

๐Ÿ–ฅ๏ธ 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)