Linear Search
So you want to find something in an array but have no idea where it is? Linear search is your best friend. It's the simplest search algorithm - just check every single element until you find what you're looking for or run out of elements. Think of it like looking for your keys in every room of your house one by one.
The beauty of linear search is its simplicity. You don't need any special conditions - your array can be sorted, unsorted, reversed, whatever. Just start at the beginning and keep checking. It's not the fastest, but it always works and it's easy to implement.
Time complexity? O(n) - worst case you check every element. Best case? O(1) if it's the first element. Average case? Still O(n). So yeah, not great for huge datasets, but perfect for small arrays or when you don't know if your data is sorted.
When to Use Linear Search
Linear search shines in specific situations. Use it when your array is small - maybe 10-20 elements. Use it when your data isn't sorted and you don't want to sort it just for one search. Use it when you're searching through a linked list where you can't jump to the middle. Use it when you need to find all occurrences of something, not just the first one.
Trust me, sometimes the simple solution is the best solution. Don't overcomplicate things with fancy algorithms when linear search does the job perfectly fine.
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const numbers = [5, 3, 8, 1, 9, 2, 7];
console.log(linearSearch(numbers, 8));
console.log(linearSearch(numbers, 4));
Try it Yourself โ