# 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"] def linear_search(array, n, x): last = array[n-1] array[n-1] = x i = 1 while array[i] != x: i += 1 array[n-1] = last if (i < n-1) or (array[n-1] == x): return i else: 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
Оригинал: “https://dev.to/sagordondev/sentinel-linear-search-4987”