Linear Search Algorithm
Dear Readers,
In this Blog today I would Share about Linear Search Algorithm a must know for everyone whether you want to are searching for a book starting with particular alphabet in bookshelf in any order, or you want to find a kid in row of children standing for the assembly(pun intended),etc. .
So, what is Linear Search?
In most simple words, It is to find a particular element in a set of given array of elements kept in any random order.
Step 1: make an array of elements.
Step 2: take the input of element you want to check in the array you made.
Step 3: then simply compare that input element or key to each and every element of your array by creating a finite loop which ends when the last element of the array is checked
# its time complexity is O(n) ,Meaning though it is simple but not very efficient especially on large arrays .😟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #1.make an array my_array = input('enter input separated with commas for split:\n').split(',') # all numbers entered are in string form so my_list =[int(i) for i in my_array] #2.take you key or whatever you want to check key = int(input('Enter key:\n')) #3.here the magic begins # called my function for action def linear_search(array,key): for index in range(len(array)): if array[index]==key: return 'Yes found your element in array at:\n%d'%(index) return -1 print(linear_search(my_list,key)) |
If you enjoyed reading this blog as much as I enjoyed writing it then do not forget to share it and subscribe for more such blogs