Contents
- search2.py
- search.py
search2.py 1/2
[top][prev][next]
# Demonstrate implementations of the linear and binary search
# techniques.
# Sara Sprenkle
# represents that the search 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.
pos = binarySearch(integers, key)
#Translate the result from binarySearch to a True or False
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()
search.py 2/2
[top][prev][next]
# Demonstrate implementation of the linear search technique.
# Two implementations: one returns either True or False;
# the other returns the position where the element was found
# Sara Sprenkle
NOT_FOUND = -1
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)
found = linearSearch(integers, key)
print("Linear: Found?", found)
if found:
print("Pos: ", linearSearchReturnPos(integers, key))
# You probably wouldn't really use both implementations
# of linear search. Just for demonstration
print()
def linearSearch(searchlist, key):
"""Returns True iff the key is in searchlist."""
for elem in searchlist:
if elem == key:
return True
return False
def linearSearchReturnPos(searchlist, key):
"""Returns the position of the key in searchlist, if found;
-1 if not found."""
for pos in range(len(searchlist)):
if searchlist[pos] == key:
return pos
return NOT_FOUND
main()
Generated by GNU Enscript 1.6.6.