What if you could find anything in a messy pile without sorting it first?
Why Linear Search Algorithm in DSA Typescript?
Imagine you have a messy drawer full of different colored socks. You want to find a red sock, but you have no idea where it is. So, you start pulling out socks one by one from the top until you find the red one.
Searching like this by hand is slow and tiring. If the red sock is at the bottom, you waste time checking every single sock. You might also lose track or miss the sock if you get distracted.
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 reaches the end.
let socks = ['blue', 'green', 'yellow', 'red', 'black']; for (let i = 0; i < socks.length; i++) { if (socks[i] === 'red') { console.log('Found red sock at position', i); break; } }
function linearSearch(items: string[], target: string): number {
for (let index = 0; index < items.length; index++) {
if (items[index] === target) {
return index;
}
}
return -1;
}
const position = linearSearch(['blue', 'green', 'yellow', 'red', 'black'], 'red');
console.log('Found red sock at position', position);Linear search lets you quickly find any item in a list without needing it to be sorted or organized.
When you look for a contact name in your phone's unsorted list, your phone uses a linear search to find the name by checking each contact one by one.
Linear search checks each item one by one until it finds the target.
It works on any list, sorted or not.
It is simple but can be slow for very large lists.