Overview
Data Structures
Searching
Linear Search is a simple search algorithm that checks every element in the list sequentially until the desired element is found or the list ends.
It works well for small or unsorted data sets but becomes slow for large data as it checks each element one by one.
// Linear Search in JavaScript
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
const result = linearSearch([5, 3, 8, 1], 8);
console.log(result); // Output: 2Linear search doesn't require sorted data — create any array to try it on.
Checks each element in order, starting from index 0, until it finds a match.
Linear search is used when the dataset is small or unsorted. It’s commonly applied when you don’t have a specific structure or index to rely on.
A good example is looking for a contact number in a small handwritten list where names are not in any order.
// Finding a name in an unsorted list
const names = ["Riya", "Ankit", "Zara", "Sam"];
const findName = (target) => {
for (let i = 0; i < names.length; i++) {
if (names[i] === target) return i;
}
return -1;
}
console.log(findName("Zara")); // Output: 2