DEV Community

Cover image for Better Linear Search
Scott Gordon
Scott Gordon

Posted on

Better Linear Search

# better_linear_search.py
#   This program uses a linear search of an array of size n for
#   value x but unlike its predecessor linear_search.py it does
#   not traverse the entire array regardless of value x being
#   discovered.  It simply returns the value immediately once
#   the value of x in found in the array.  If not found then it 
#   will just return text saying it wasnt found.
# by: Scott Gordon

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

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

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 (0)