Linear search : What it is and how to implement it in python ?
In this tutorial, we will learn about the standard Linear search algorithm and will implement it in Python.
Linear Search in Python
In linear search, the search element is compared with each element in the list, starting from the beginning of the list. This continues till either the element has been found or you have reached the end of the list.
That is why this type of searching technique is called Linear Search.
TIME COMPLEXITY of Linear Search:
The time complexity of above algorithm is O(n), where n is the number of elements in the list.
SPACE COMPLEXITY of Linear Search:
Linear Search takes constant space irrespective of the number of elements in the array taking the space required to be of the range O(1).
DISADVANTAGE of Linear Search:
If the element to be searched is towards the end of the array, the searching process becomes very time consuming because the algorithm searches for the element in a sequential manner starting from the first element.
Implementation in Python
data_list=list(map(int , input().split())) value=int(input()) flag=0 for i in range(0,len(data_list)): if(data_list[i]==value): print("Element found at :" + str(i)) flag=1 break if(flag==0): print("Search not succesful")
1 14 26 39 45 52 12 432 321 54 45
Element found at :4
That’s it! Hope you have understood the concept of Binary Search.
Feel free to leave any doubts regarding the algorithm in the comments section below.
Also, have a look at other posts too,