# sentinel_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 utilizes
# a sentinel value in the arrays last index as a placeholder
# ensuring that only one check takes place becuase you will not be
# checkinf for the array length, just the search term x
# This algorithm is more efficient than either linear_search.py or
# better_linear_search.py.
# by: Scott Gordon
things=["bike","house","cat","computer","hammer"]deflinear_search(array,n,x):last=array[n-1]array[n-1]=xi=1whilearray[i]!=x:i+=1array[n-1]=lastif (i<n-1)or(array[n-1]==x):returnielse:return"Not found!"print(linear_search(things,5,"cat"))# prints the index of "cat" which is 2
# prints the index of "hammer" which is 4
print(linear_search(things,5,"hammer"))print(linear_search(things,5,"pasta"))# prints Not found
print(linear_search(things,5,"junk"))# prints Not found
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)