Linear Search Technique
- Suppose you have a single key which may or may not open one of the five doors given below.
- We can try to unlock doors one by one randomly.
- Or we can also start from either end and try to unlock doors in a sequential order, this is known as linear search.
- If one of the doors is unlocked then search is successful otherwise search is unsuccessful.
- This algorithm search an element in a given list by comparing an item with each of the elements of list one by one.
- We can start from first element and search upto last element (o to n-1).
- Or we can also start from the last element and search till the first element (n-1 to 0).
- In both of the cases each location of the array is searched once.
- Suppose we want to find location of element 15 in Array given below:
- We will start comparing 15 with each of the elements of array one by one starting from a[0] to a[4].
- If element is found then we will return its location otherwise we will return-1 treated as an invalid index of Array.
- Firstly we will compare 15 with a[0] i.e. 22 which are not equal so, we will compare it with next element a[1] i.e. 5, again both are not equal.
- We will continue our search process until we find our element or if we exceed upper bound of our Array.
- In our case item is found at index "3" of given array so, 3 will be returned. item=15
- There might be situation where array elements are duplicate in that case our algorithm will return the index of first occurrence.
- If given element is not present in the list then our algorithm will return-1 which is treated as an invalid array index in our case.
- In this case "2" will be returned as first occurrence of 15 is found at index 2 of our given Array.
Linear Search Time Complexity
- In Best case item will be found in only one comparison i.e. at "0" index of the array. So, it is constant i.e. o(1).
- In Worst case either item will be found at last index of Array i.e. "n-1" or item is not present in the Array both of which requires total of "n" comparisons. So, it is O(n).
- If element is found at location "0" then it will take 1 comparison
- if it is found at location 1" then it will take 2 comparisons
- if it is found at location "n-1 then it will take 'n" comparisons.







