There are many cases in computer programming we need to search for an element in a collection of data. The Unordered Linear Search is one of the simplest searching algorithms.
def unordered_linear_search(search_list, data): for i in range(len(search_list) - 1): if search_list[i] == data: # We have found the item at index i return i # If we got here, we didn't find the item return None if __name__ == '__main__': names = ['Bob Belcher', 'Linda Belcher', 'Tina Belcher', 'Gene Belcher', 'Louise Belcher'] linda_index = unordered_linear_search(names, 'Linda Belcher') if linda_index: print('Linda Belcher found at ', str(linda_index)) else: print('Linda Belcher was not found') teddy_index = unordered_linear_search(names, 'Teddy') if teddy_index: print('Teddy was found at ', str(teddy_index)) else: print('Teddy was not found')
In this code, we are basically looping through the search_list object until we found a match. If we found the match, we return the index of the item’s location. Otherwise, we return Python’s None object to indicate the item wasn’t found. When run, the program will produce this output.
Linda Belcher found at 1 Teddy was not found
For the search for loop, why not just the following? Is there any reason?
for s in search_list:
if s == data:
# We have found the item at index i
return i
LikeLike
We are looking for the index not the element. Normally we I would use indexOf, but this post is geared towards students who have to learn this algorithm. Good question!
LikeLike