What if you could find anything in a messy list without missing a single item?
Why Linear Search Algorithm in DSA Javascript?
Imagine you have a messy drawer full of different colored socks, and you need to find a red sock. You start picking up each sock one by one, checking its color until you find the red one.
Searching this way can take a long time if the drawer is big. You might miss the sock or get tired, making mistakes. It's slow and frustrating to check every single sock manually.
The linear search algorithm does exactly what you do but faster and without mistakes. It checks each item in a list one by one until it finds the target, making the search simple and reliable.
const socks = ['blue', 'green', 'yellow', 'red', 'black']; let found = false; for (let i = 0; i < socks.length; i++) { if (socks[i] === 'red') { found = true; break; } }
function linearSearch(items, target) {
for (let index = 0; index < items.length; index++) {
if (items[index] === target) {
return index;
}
}
return -1;
}It lets you quickly find any item in a list, no matter how messy or unordered it is.
Finding a friend's name in a list of contacts on your phone when you don't know if the list is sorted.
Linear search checks items one by one until it finds the target.
It works on any list, sorted or not.
It's simple but can be slow for very large lists.