The Linear Search Algorithm is a very interesting question that you may have heard in your school or college asked in many interviews including FAANG companies.  


In computer science, linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. The linear search runs at the worst linear time and makes most n comparisons, where n is the length of the list.

Time Complexity: O(n) - since in the worst case we're checking each element exactly once.


Example 1:

Input: array = [7,2,8,5,6], searchParam = 8, n(length of array) = 5

Output: 2


Example 2:

Input: array = [7,2,8,5,6], searchParam = 10, n(length of array) = 5

Output: -1


Let's start with the algorithm,


var linearSeach = function(array, searchParam, n) {

  for(let i=0;i<n;i++)

  {

    if(array[i]==x)

    {

      return i;

    }

  }

  return -1;

}


Here, We compare array elements one by one with searchParam and when that parameter is found then it will return the value of i which is the index of that searchParam. If searParam is not found in the array then the result will be -1.


I hope you understood the algorithm. If you have any doubts, please let us know in the comments.