# file: search.py # # author: Bob Muller # date: November 7, 2007 # # This file contains two search functions, linearSearch and # binarySearch. # # linearSearch looks for an item starting at the front of an arbitrary # list and working it's way to the back of the list. On average, if the # list contains n items, linearSearch will perform n/2 comparisons. # When n is 1,000,000,000, for example, linearSearch will perform # 500,000,000 comparisons. # # binarySearch works only for orderered lists. It starts looking for # the item in the middle of the list. If the item isn't found, it will # recursively look on either side. binarySearch will perform log_2 n # comparisons on average. When n is 1,000,000,000, only 30 comparisons # are required. def linearSearch(item,lst): # print the list for illustration purposes. # print lst if lst == []: return False else: return (item == lst[0] | linearSearch(item,lst[1:])) def binarySearch(item,lst): # print the list for illustration purposes. # print lst if lst == []: return False else: mid = len(lst) / 2 if item == lst[mid]: return True else: if item > lst[mid]: return binarySearch(item, lst[mid+1:]) else: return binarySearch(item, lst[:mid])