I am trying to generate 100 separate lists of 500 positive integers and run each algorithm on the 100 lists. This is meant to represent a worst-case analysis, so I am searching for an element I know will not be in the lists (-1).
The main() function is meant to be used to print the results i.e. "Sequential Search took xx seconds to run, on average."
I have tried passing the get_me_random_list function as a parameter for the algorithm functions, but that was unsuccessful.
def main():
sequential_search(a_list, -1)
ordered_sequential_search(a_list, -1)
binary_search_iterative(a_list, -1)
binary_search_recursive(a_list, 1)
def get_me_random_list():
a_list = []
for i in range(100):
a_list.append(random.sample(range(1,500), 100))
return a_list
def sequential_search(a_list,item):
start = time.time()
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos + 1
end = time.time()
return found
print(f"Total runtime of the sequential search is {end - begin}")
def ordered_sequential_search(a_list,item):
start = time.time()
pos = 0
found = False
stop = False
while pos < len(a_list) and not found and not stop:
if a_list[pos] == item:
found = True
else:
if a_list[pos] > item:
stop = True
else:
pos = pos + 1
end = time.time()
return found
print(f"Total runtime of the ordered sequential search is {end - begin}")
def binary_search_iterative(a_list,item):
start = time.time()
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if a_list[midpoint] == item:
found = True
else:
if item < a_list[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
end = time.time()
return found
print(f"Total runtime of the binary search iterative is {end - begin}")
def binary_search_recursive(a_list,item):
start = time.time()
if len(a_list) == 0:
return False
else:
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True
else:
if item < a_list[midpoint]:
return binary_search(a_list[:midpoint], item)
else:
return binary_search(a_list[midpoint + 1:], item)
end = time.time()
return found
print(f"Total runtime of the binary search recursive is {end - begin}")
if __name__ == "__main__":
main()