Linear search, also known as sequential search, is an algorithm where we look for an item in a list by comparing each item one by one. It’s a straightforward algorithm that we use every day.
Example
Given an array arr = [4, 1, 3, 2] and we are looking for our target to search s = 3, we compare the values at each index one by one until it is found.

Note
- Linear search can be performed on both sorted and unsorted data
- We return the index/position of the element if found else return -1 if not found
Linear Search Algorithm
LinearSearch(List, Value)
for all items in the list
if item == value
return its position
else return not foundCode language: JavaScript (javascript)JavaScript Code
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const arr = [4, 1, 3, 2, 5];
console.log(linearSearch(arr, 2));
// Output: 3 (i.e at index 3 of the array we have 2)
console.log(linearSearch([3.14, 2.71, 1.61, 0.57], 1.61));
// Output: 2
console.log(linearSearch(['apple', 'banana', 'cherry'], 'banana'));
// Output: 1
console.log(linearSearch([12, 3, 45, 6, 78], 100));
// Output: -1Code language: JavaScript (javascript)Time Complexity: O(N)
