top of page
  • LinkedIn
  • Facebook
  • YouTube
  • Twitter
  • Instagram
  • Pinterest
  • Tumblr
  • Vkontakte

Linear Search: Searching Made Easy

Updated: Jun 3, 2022


Algorithm


Linear search is one of the simplest searching algorithms. Linear search finds the target element by sequentially checking every element in the given input array. This is why linear search is sometimes also referred to as sequential search. Linear search works on both sorted and unsorted arrays.


For an input array arr and a target element lets say x, linear search does the following steps:

  1. Iterate through the input array from start to end (or end to start, traversal order does not matter).

  2. In each iteration compare the current element to the target element x.

  3. If current element is equal to the target element x, you have found the element you are looking for. Stop the iteration and return the current element index as result.

  4. If current element is not equal to x, continue to the next element and repeat the above steps until you find the target element or you have reached the end of the array. If the target element x is not found then return -1 as the result indicating the target value is not present in the given array.


Working


Consider the given input array is [3, 7, 1, 5, 11] and the target element x=1 as shown below:



Lets say i is our index variable. Linear search algorithm starts by checking the element at index 0, as shown in the below diagram.