Contents

  1. search_compare.py
  2. search.py

search_compare.py 1/2

[
top][prev][next]
# Compare the searching techniques by the number of comparisons.
# by Sara Sprenkle, 11.28.2007

def main():

    print "This program helps us to empirically compare search strategies"
    print

    KEYS = [1, 4, 13, 19, 125, 126, 127]
    NUM_ENTRIES = 10000
    
    integers = range(1,NUM_ENTRIES*2,2)
    #print integers
    print "Creating list of size", NUM_ENTRIES*2, "starting at 1 and incrementing by 2"
    print

    print "%4s|%10s" % ("","# Comparisons")
    print "%4s| %5s %5s" % ("KEY", "LIN", "BIN")
    print "-"* 20
    
    for key in KEYS:
        lin_comp = linearSearch(integers,key)
        bin_comp = binarySearch(integers,key)
        print "%4d| %5d %5d" % (key, lin_comp, bin_comp)


# Return the number of comparisons required to find the key.
def linearSearch(ls, key):
    numChecks = 0
    for elem in ls:
        numChecks += 1
        if elem == key:
            return numChecks
    return numChecks

# Return the number of comparisons required to find the key.
def binarySearch(searchlist, key):
    low = 0
    high = len(searchlist)-1
    numChecks = 0
    while low <= high:
        mid = (low+high)/2
        numChecks+= 2
        if searchlist[mid] == key:
            return numChecks
        numChecks+=1
        if searchlist[mid] < key:
            low = mid+1
        else:
            high = mid-1
    return numChecks

main()

search.py 2/2

[
top][prev][next]
# Demonstrate implementations of the linear and binary search
# techniques.
# Sara Sprenkle, 11.28.2007

def main():
    
    integers = range(1,20,2)
    print integers
    
    print "*",1,"*"
    print "Linear: Found?", linearSearch(integers,1)
    print "Binary: Found at pos", binarySearch(integers,1)

    print "*",4,"*"
    print "Linear: Found?", linearSearch(integers,4)
    print "Binary: Found at pos", binarySearch(integers,4)
    
    print "*",15,"*"
    print "Linear: Found?", linearSearch(integers, 15)
    print "Binary: Found at pos", binarySearch(integers, 15)

    print "*",16,"*"
    print "Linear: Found?", linearSearch(integers, 16)
    print "Binary: Found at pos", binarySearch(integers, 16)
    
    print "*",17,"*"
    print "Linear: Found?", linearSearch(integers, 17)
    print "Binary: Found at pos", binarySearch(integers, 17)


def linearSearch(searchlist, key):
    for elem in searchlist:
        if elem == key:
            return True
    return False

def binarySearch(searchlist, key):
    low = 0
    high = len(searchlist)-1
    while low <= high:
        mid = (low+high)/2
        if searchlist[mid] == key:
            return mid
        if searchlist[mid] < key: # search lower half
            low = mid+1
        else: # search upper half
            high = mid-1
    return -1

main()

Generated by GNU enscript 1.6.4.