Algorithm: Linear Search
- FUNCTION: Search
- PERFORMANCE: О(n)
- FOUNDED IN: Ancient
- FOUNDED BY: Anonymous
One of the most common and basic algorithms, linear search goes through a collection and sequentially checks each item until the term being searched matches one of the items in the collection (such as a list).
Here is an illustration showing the search process of number 802:
STEP BY STEP
Below, you can see a simple Python code showing a linear search algorithm implementation.
Algorithms can be so much fun indeed. If you’ve started to learn coding recently it can be very fulfilling to fully understand an algorithm and code it on your own.
This algorithm is very suitable for a new programmer to build from scratch and if you have time and interest you are definitely encouraged to do so. Enjoy!
LINEAR SEARCH ALGORITHM CODE IN PYTHON
#Linear Search Algorithm
lst = [44, 2, 13,52, 802, 44]
def lin_search(x):
for i in range(len(lst)):
if lst[i] == x:
return "Your term's index is: "+str(i)
if not found:
return "Your search term can not be found."
print(lin_search(802))
Your term’s index is: 4
Linear Search Algorithm above also demonstrates so many fundamental concepts in Python such as: Lists, For Loops, User-defined Functions, Type Conversion, return statement, Conditional Statement (if) and len() function.
Linear Search is also known as sequential search and is a quite useful algorithm beside being very simple to implement. It’s shortcoming becomes visible when used on large datasets in which case other search algorithms will likely be more useful.