What if you could find anything in a messy list without sorting it first?
Why Linear Search Algorithm in DSA C++?
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.
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 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.
int findIndex(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) return i;
}
return -1;
}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;
}Linear search lets you quickly find any item in a list without needing it to be sorted or organized.
Finding a friend's phone number in a small, unsorted contact list by checking each entry until you find the right one.
Linear search checks each item one by one.
It works on any list, sorted or not.
Simple but can be slow for big lists.