def linear_search(data, to_find):
found = False # flag for while loop
index = 0 # for marking position
while not found:
if index > len(data) - 1: # if looped through and still not found
print(f"'{to_find}' is not in the list.")
found = True # end while
elif data[index] == to_find: # found a match
print(f"The word '{to_find}' was found at position {index}!")
found = True # end while
else:
index += 1 # check the next element
def binary_search(data, to_find):
data.sort() # items must be sorted before searching
found = False # flag for the while loop
lower = 0 # marker for the first element in list/sublist
upper = len(data) - 1 # marker for last element in list/sublist
while lower <= upper and found == False: # check lower and upper haven't crossed
mid = (lower + upper) // 2 # find the midpoint, int division to round down
if data[mid] == to_find:
found = True # end while
else:
if data[mid] < to_find:
lower = mid + 1 # move lower marker up, one AFTER the midpoint
else:
upper = mid - 1 # move upper marker down, one BEFORE the midpoint
if found == True:
print(f"The word '{to_find}' was found at position {mid}!")
else:
print(f"'{to_find}' is not in the list.")
data = ["freedom", "revolution", "sacred", "question", "conceive", "yearn", "lane", "promotion", "meal", "wander", "nomination", "forget", "foundation", "learn", "roof"]
to_find = input("Enter a word to find").lower()
binary_search(data, to_find)