Linear search algorithm in javascript

An simple algorithm to search an item in a given array.

We will implement a simple linear search algorithm to search an item in a given array in javascript. Everything will be written in ES6.

Example

Input:
[1, 2, 3, 4, 5, 6, 10, 11, 15]
5
12
11

Output:
true
false
true

Implementation

  • We will iterate through each item in the given array.
  • Then in each iteration we will check if element is present or not in the array.
  • If it is present then return true else return false.
 let linearSearch = (arr, item) => {
   let found = false;
   
   //loop through each item in the array
   for(let elements of arr){
      if(elements === item){
         found = true;
         break;
      }
   }

   return found;
 };
Input:
console.log(linearSearch([1, 2, 3, 4, 5, 6, 7, 8], 7));
console.log(linearSearch(['prashant','yadav', 23, 25, 27], 'yadav'));
console.log(linearSearch([true, true, true, true], false));

Output:
true
true
false

Time complexity: O(n).
Space complexity: O(1).

Time and Space complexity

  • We are iterating through each item in the given array, so Time complexity is O(n).
  • We are using constant space, so Space complexity is O(1).

Another solution.

We can also implement linear search algorithm by searching for an item in array with array’s inbuilt indexof function of javascript.

 let linearSearch = (arr, item) => {
   return arr.indexOf(item) !== -1 ? true: false;
 }
Input:
console.log(linearSearch([1, 2, 3, 4, 5, 6, 7, 8], 7));
console.log(linearSearch(['prashant','yadav', 23, 25, 27], 'yadav'));
console.log(linearSearch([true, true, true, true], false));

Output:
true
true
false

Time complexity: O(n).
Space complexity: O(1).

Time and Space complexity

  • We are using indexOf method to check if item exists in the given array, so Time complexity is O(n).
  • We are using constant space, so Space complexity is O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *