# 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!
![Cover image for Better Linear Search](https://media.dev.to/cdn-cgi/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu800ejov1bdes3rh6vcn.jpg)
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)