Implement the sorting algorithm you came up with in pseudocode with Python
In [94]:
# This code works for positive integers and assumes the list is already sorted
def binary_search(list, value):
high = len(list) - 1;
low = 0;
#print("The length of the list is", len(list))
#counter is used to track the index point
#that the binary_search is looking at
counter = int((high+low)/2) # start by looking at the middle
#if the list is empty do not proceed!
if len(list) == 0:
return 0
while low < high: # and counter <= high
#print("counter is", counter)
#print(list[counter])
#print(value)
if list[counter] == value:
return print("Value of", value, "was found at the index", counter)
elif low < value < list[counter]:
high = list[counter - 1]
counter = counter -1
elif value == 0:
if list[0] == 0:
return print("Value of", value, "was found at the index 0")
else:
return print("Unfortunately", value, "was not found in this list.")
else:
low = list[counter]
counter = counter + 1
return print("Unfortunately", value, "was not found in this list.")
In [95]:
binary_search([1,2,3,4], 0)
In [96]:
def sort(list):
times = len(list) - 1
# create a new empty list to add sorted values
sorted = []
while times + 1> 0:
min = list[0]
for item in list:
if item < min:
min = item
# after finding the smallest element, append it to the new sorted list
sorted.append(min)
#remove the smallest element from the original list
list.remove(min)
#incremenet the number of times, in order to get closer to the condition
# that will halt this while loops
times = times - 1
return sorted
In [97]:
from random import randint
def random_num_gen(x):
random_list = []
count = 0
while count < x:
random_list.append(randint(0,100))
count = count + 1
return random_list
ten_sample = random_num_gen(10)
hundred_sample = random_num_gen(100)
thousand_sample = random_num_gen(1000)
In [98]:
thousand_sample = sort(thousand_sample)
ten_sample = sort(ten_sample)
hundred_sample = sort(hundred_sample)
In [99]:
%time binary_search(thousand_sample, 35)
In [ ]:
print(hundred_sample)
In [100]:
%time binary_search(hundred_sample, 31)
In [101]:
%time binary_search(hundred_sample, 45)
In [102]:
print(ten_sample)
In [103]:
type(hundred_sample)
Out[103]:
In [104]:
%time binary_search(ten_sample, 99)
In [105]:
print(ten_sample)
In [107]:
%time binary_search(hundred_sample, 15)
In [108]:
%time binary_search(hundred_sample, 3)
In [109]:
%time binary_search(hundred_sample, 343)
In [110]:
%time binary_search(ten_sample, 32)
In [ ]: