0
0
DSA C++programming~3 mins

Why Linear Search Algorithm in DSA C++?

Choose your learning style9 modes available
The Big Idea

What if you could find anything in a messy list without sorting it first?

The Scenario

Imagine you have a messy drawer full of different colored socks, and you want to find a red sock. You start picking up each sock one by one, checking its color until you find the red one.

The Problem

Doing this by hand is slow and tiring, especially if the drawer is very full. You might lose track or miss some socks, making the search frustrating and error-prone.

The Solution

The linear search algorithm works just like checking each sock one by one, but it does it quickly and without mistakes. It goes through each item in a list until it finds the one you want or finishes checking all.

Before vs After
Before
int findIndex(int arr[], int size, int target) {
  for (int i = 0; i < size; i++) {
    if (arr[i] == target) return i;
  }
  return -1;
}
After
int linearSearch(const std::vector<int>& data, int target) {
  for (size_t index = 0; index < data.size(); ++index) {
    if (data[index] == target) return static_cast<int>(index);
  }
  return -1;
}
What It Enables

Linear search lets you quickly find any item in a list without needing it to be sorted or organized.

Real Life Example

Finding a friend's phone number in a small, unsorted contact list by checking each entry until you find the right one.

Key Takeaways

Linear search checks each item one by one.

It works on any list, sorted or not.

Simple but can be slow for big lists.