Linear Search is a searching technique to search some particular value from an array. This is the simplest searching technique.
In this searching technique,
the value to be searched is compared with all the elements in the array.
If the value is found, the index of the element is returned.
If the particular element is not present throughout the array, then return -1 or some relevant string message.
linearSearch(int array, int value): for i=0 to len(array): if(array[i]==value): Element is Present //outside for loop Element Not Present // element not found in the whole array
def linearSearch(arr,value): for i in range(len(arr)): if(arr[i]==value): return i return -1 array=[1,2,3,4,5,6,7,8,9,10] value=5 a=linearSearch(array,value) if(a==-1): print("Element not present") else: print("Element present at index",a)
Element present at index 4
The worst case time complexity of linear search is O(n). The worst case occurs when the element is present at the last index of the array or not present at all.
The best case time complexity of linear search is O(1). The best case occurs when element is present at the first index of the array.
The worst case complexity of linear search can be improved to O(n/2). This can be done using two pointers, left and right and carrying on two comparisons at a time, hence reducing the worst case time complexity of linear search to O(n/2).
def linearSearch(arr,value): left=0 right=len(arr)-1 while(left<=right): if(arr[left]==value): return left elif(arr[right]==value): return right left+=1 right-=1 return -1 array=[1,2,3,4,5,6,7,8,9,10] value=10 a=linearSearch(array,value) if(a==-1): print("Element not present") else: print("Element present at index",a)
Element present at index 9
In the above example, the element present at the last index, is found in the first iteration itself. Using the first method, it would have taken 10 iterations to find this element.
If the element is not found, the worst case complexity is O(n/2), since the total number of iterations are n/2 in the second method.
Linear search is rarely used since there are better searching algorithms such as binary search which provide better time complexities. Linear search is not efficient for large input array.