DEV Community

Cover image for Linear Search
Scott Gordon
Scott Gordon

Posted on

Linear Search

# linear_search.py
#   This program uses a linear search of an array of size n for
#   value x 
# by: Scott Gordon

things = ["bike", "house", "cat", "computer", "hammer"]

def linear_search(array, n, x):
    answer = "Not found!"
    for i in range(1, n):
        if array[i] == x:
            answer = i
    return answer

print(linear_search(things, 5, "cat")) # prints the index of "cat" which is 2
print(linear_search(things, 5, "hammer")) # prints the index of "hammer" which is 4
print(linear_search(things, 5, "pasta")) # prints Not found!
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
diegofranco2001 profile image
DiegoFranco2001

Why not this? It break the loop when find the element, there is another way by getting the length of the array too. :D

def linear_search (array, element):
    for i, e in enumerate(array):
        if array[i] == element:
            return i
    return "Not found!"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sagordondev profile image
Scott Gordon

yeah, i had added that to the better linear search algo after this one. And yes using len(array) is more Pythonic but I was trying to write it as close to psuedocode as possible while still using Python.

Thanks for the suggestions though!