"""File: srch_tst2.py Purpose: Compare the run-time of binary search, linear search, and dictionary search on a list of ints Run: python srch_tst2.py Input: The number of ints in the data structure. The number of values to search for. Output: The average time it took to search the list using binary and linear search and a dictionary. """ from random import randint from time import time #---------------------------------------------------------------------- def dict_srch(d, key): """Search the dictionary d for key""" if d.has_key(key): return d[key] else: return None #---------------------------------------------------------------------- def bin_srch(l, min, max, key): """See if key belongs to l between subscript min and subscript max""" if (min <= max): mid = (min+max)/2 if key == l[mid]: return mid elif key < l[mid]: return bin_srch(l, min, mid-1, key) else: # key > l[mid] return bin_srch(l, mid+1, max, key) else: # min > max. key not in list return None #---------------------------------------------------------------------- def lin_srch(l, key): """Use linear search to try to find key in l""" for i in xrange(len(l)): if l[i] == key: return i return None #---------------------------------------------------------------------- def gen_list(n, max): """Generate a list of n random ints in the range 0--max""" l = [] for i in xrange(n): l.append(randint(0,max)) return l #---------------------------------------------------------------------- def gen_dict(l): """Create a dictionary from the list l""" d = dict() count = 0 for i in l: d[i] = count count = count+1 return d #---------------------------------------------------------------------- # Main program n = int(raw_input("How many elements in the list?\n ")) srch_count = int(raw_input("How many elements should we search for?\n ")) l = gen_list(n, 2*n) l.sort() d = gen_dict(l) #print "l =", l #print "d =", d srch_keys = gen_list(srch_count, 2*n) #print "srch_keys =", srch_keys start = time() for i in xrange(srch_count): loc = bin_srch(l, 0, n-1, srch_keys[i]) # print "bin_srch: ", srch_keys[i], "in loc", loc finish = time() bin_srch_time = finish-start; print "Average time for bin search =", bin_srch_time/srch_count start = time() for i in xrange(srch_count): loc = lin_srch(l, srch_keys[i]) # print "lin_srch: ", srch_keys[i], "in loc", loc finish = time() lin_srch_time = finish-start; print "Average time for lin search =", lin_srch_time/srch_count start = time() for i in xrange(srch_count): loc = dict_srch(d, srch_keys[i]) # print "dict_srch: ", srch_keys[i], "in loc", loc finish = time() dict_srch_time = finish-start; print "Average time to dict search for =", dict_srch_time/srch_count