Linux, OpenSource, Programming And Hacks

Jul 20, 2017

Python Program for Linear Search using For loop

Jul 20, 2017
In linear search algorithm we match the element to be searched with the entire list of elements. Therefore its a brute force approach.

time complexity: O(n)

Linear Search implementation in Python:

list_of_elements = [4, 2, 8, 9, 3, 7]

x = int(input("Enter number to search: "))

found = False

for i in range(len(list_of_elements)):
 if(list_of_elements[i] == x):
  found = True
  print("%d found at %dth position"%(x,i))
if(found == False):
 print("%d is not in list"%x)

Also check out Binary Search Algorithm for a better Time complexity O(log n)

No comments:

Post a Comment