Contents

  1. linear_and_binary_search.py
  2. linear_search.py
  3. search_compare.py
  4. search_divide.py

linear_and_binary_search.py 1/4

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

# represents that binarySearch did not find the key
NOT_FOUND=-1

def main():
    
    integers = range(1,20,2)
    print("The list to search: ", integers)
    print()
    
    findMeList = [1, 4, 15, 16, 17]
    
    for key in findMeList:
        print("Search for", key)
        print("Linear: Found?", linearSearch(integers, key))
        # binarySearch returns the position the number was found, or -1 if it was
        # not found.  Translate the result from binarySearch to a True or False
        pos = binarySearch(integers, key)
        binFound = pos != NOT_FOUND
        print("Binary: Found?", binFound)
        print()
    

def linearSearch(searchlist, key):
    "Returns true iff key is in the list of integers searchlist"
    for elem in searchlist:
        if elem == key:
            return True
    return False

def binarySearch(searchlist, key):
    """ Returns the position where key (an int) is found in the list of sorted
    integers searchlist or -1 if key is not in the list. """
    
    low = 0
    high = len(searchlist)-1
    while low <= high:
        mid = (low+high)//2
        valueAtMid = searchlist[mid]
        if valueAtMid == key:
            return mid
        if valueAtMid < key: # search upper half
            low = mid+1
        else: # search lower half
            high = mid-1
    return NOT_FOUND
    
main()

linear_search.py 2/4

[
top][prev][next]
# Demonstrate implementation of the linear search technique.
# Sara Sprenkle

def main():
    
    integers = range(1, 20, 2)
    print("The list we are searching: ", integers)
    print()
    
    findMeList = [1, 4, 15, 16, 17]
    
    for key in findMeList:
        print("Search for", key)
        print("Linear: Found?", linearSearch(integers, key))
        print()


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

main()

search_compare.py 3/4

[
top][prev][next]
# Compare the linear and binary searching techniques by the number of
# comparisons.
# by Sara Sprenkle

def main():

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

    # The keys I want to search for in a list
    #keys = [1, 4, 13, 19, 125, 126, 127]
    keys = [1, 4, 13, 19, 125, 126, 127, 19997, 19998, 19999]

    NUM_ENTRIES = 10000
    
    # the list of integers that I'm searching (odd numbers)
    integers = list(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("{:6s}| {:14s}".format("","# Comparisons"))
    print("{:6s}| {:>6s} {:>6s}".format("KEY", "LIN", "BIN"))
    print("-"* 24)
    
    total_lin_comp = 0.0
    total_bin_comp = 0.0
    
    for key in keys:
        lin_comp = linearSearch(integers,key)
        bin_comp = binarySearch(integers,key)
        print("{:6d}| {:6d} {:6d}".format(key, lin_comp, bin_comp))
        
        # update the total number of comparisons
        total_lin_comp += lin_comp
        total_bin_comp += bin_comp
    
    print()
    print("ON AVERAGE...")
    print("-"*50)
    print()
    print("The average number of comparisons per search for")
    print("\tlinear search was", total_lin_comp/len(keys))
    print("\tbinary search was", total_bin_comp/len(keys))
    print()
    print("Disclaimer: May not be a completely fair comparison but gives us an idea.")


# Return the number of comparisons required to find the key.
def linearSearch(searchlist, key):
    numChecks = 0
    for elem in searchlist:
        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  # while comparison, next if comparison
        if searchlist[mid] == key:
            return numChecks
        numChecks+=1
        if searchlist[mid] < key:
            low = mid+1
        else:
            high = mid-1
    return numChecks

main()

search_divide.py 4/4

[
top][prev][next]
# Binary search, dividing list in half
# Sara Sprenkle

# represents that binarySearch did not find the key
NOT_FOUND=-1

def main():
    
    integers = range(1,20,2)
    print("The list to search: ", integers)
    print()
    
    findMeList = [1, 4, 15, 16, 17]
    
    for key in findMeList:
        print("Search for", key)
        # binarySearch returns the position the number was found, or -1 if it was
        # not found.  Translate the result from binarySearch to a True or False
        pos = altBinarySearch(integers, key)
        binFound = pos != NOT_FOUND
        print("Binary: Found?", binFound)
        print()

def altBinarySearch(searchlist, key): 
    """Literally divide the list in half. Issues: creates multiple lists.
    Each call to the function requires another list (of half the size of
    the original)."""

    # ran out of elements in the list    
    if len(searchlist) == 0:
        return NOT_FOUND

    low = 0
    high = len(searchlist)-1
    mid = (low+high)/2
    
    valueAtMid = searchlist[mid]
    if valueAtMid == key:
        return mid
    if low == high:
        return NOT_FOUND    

    if searchlist[mid] < key: # search upper half
        return altBinarySearch(searchlist[mid+1:], key)
    else: # search lower half
        return altBinarySearch(searchlist[:mid], key)
        
main()

Generated by GNU Enscript 1.6.6.