"""File: bin_srch_tst.py Purpose: Compare the run-time of binary search and linear search of a list of ints Run: python bin_srch_tst.py Input: The number of ints in the list. The number of values to search for. Output: The average time it took to search the list using binary and linear search. """ from random import randint from time import time def bin_srch(l, min, max, val): """See if val belongs to l between subscript min and subscript max""" if (min <= max): mid = (min+max)/2 if val == l[mid]: return mid elif val < l[mid]: return bin_srch(l, min, mid-1, val) else: # val > l[mid] return bin_srch(l, mid+1, max, val) else: # min > max. val not in list return None #---------------------------------------------------------------------- def lin_srch(l, val): """Use linear search to try to find val in l""" for i in xrange(len(l)): if l[i] == val: return i return None #---------------------------------------------------------------------- def gen_list(l, n, max): """Generate a list of n random ints""" for i in xrange(n): l.append(randint(0,max)) #---------------------------------------------------------------------- # 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(l, n, 2*n) l.sort() #print "l =", l srch_vals = [] gen_list(srch_vals, srch_count, n) #print "srch_vals =", srch_vals start = time() for i in xrange(srch_count): loc = bin_srch(l, 0, n-1, srch_vals[i]) # print "bin_srch: ", srch_vals[i], "in loc", loc finish = time() bin_srch_time = finish-start; print "Average time for binary search =", bin_srch_time/srch_count, "seconds" start = time() for i in xrange(srch_count): loc = lin_srch(l, srch_vals[i]) # print "lin_srch: ", srch_vals[i], "in loc", loc finish = time() lin_srch_time = finish-start; print "Average time for linear search =", lin_srch_time/srch_count, "seconds"