import time def search(L, value): '''Return the index of value in L, or len(L) if value doesn't exist in L.''' i = 0 # The current index in L. while i < len(L) and L[i] != value: i += 1 return i def sentinel_search(L, value): '''Return the index of value in L, or len(L) if value doesn't exist in L.''' L.append(value) i = 0 # The current index in L. while L[i] != value: i += 1 L.pop() return i def binary_search(L,v): """Return the index of the leftmost occurrence of v in list L, or -1 if v is not in L.""" i = 0 j = len(L) - 1 while i != j + 1: m = (i + j) / 2 if L[m] == v: print m return m elif L[m] < v: i = m + 1 else: j = m - 1 if 0 <= i < len(L) and L[i] == v: return i else: return -1 if __name__ == "__main__": L = range(1000000) t1 = time.time() print sentinel_search(L, 999999),'sb 999999' t2 = time.time() print "sentinel search:", t2 - t1 t1 = time.time() print search(L, 999999), 'sb 999999' t2 = time.time() print "search:", t2 - t1 t1 = time.time() print binary_search(L, 999999), 'sb 999999' t2 = time.time() print "binary search:", t2 - t1