Table of contents
No headings in the article.
Sequentially checks the target value in given list and match found.
Time Complexity: best : O(1) Worst: O(n)
Space Complexity: O(1)
function linearSearch(arr, target) {
for (let i in arr) {
if(arr[i] === target) return i;
}
return -1;
};
linearSearch([1,2,3,4], 3);
> '2'
linearSearch([1,2,3,4], 5);
> -1
Linear search is best to use while searching in unsorted array.
JS indexOf(), includes(), find() & findIndex()
implemented using linear search.