Skip to content

Instantly share code, notes, and snippets.

@Hwatwasthat
Created March 1, 2018 15:53
Show Gist options
  • Select an option

  • Save Hwatwasthat/c91a2a4c5502b9e4db1337c2e2f54a5c to your computer and use it in GitHub Desktop.

Select an option

Save Hwatwasthat/c91a2a4c5502b9e4db1337c2e2f54a5c to your computer and use it in GitHub Desktop.
Binary search created by Hwatwasthat - https://repl.it/@Hwatwasthat/Binary-search
import random, time
k = 0
def sorted_list(a, b):
test = random.sample(range(a), b)
test.sort()
return test
def binary_search(sorter, num_find):
print (sorter)
# loop for sorter
while int(len(sorter)) > 1:
# Calculate halfway point of list
halfway = (len(sorter) // 2)
#if the number at halfway is the one being looked for
if sorter[halfway] == num_find:
return True
#if the number is higher than halfway point, cut the list with halfway being the new 0 point
elif sorter[halfway] < num_find:
sorter = sorter[halfway : len(sorter)]
#print(sorter)
#if the number is lower than halfway point, cut the list with halfway being the new end
elif sorter[halfway] > num_find:
sorter = sorter[0 : halfway]
#print(sorter)
#do a final check if num not been found
if sorter == num_find: return True
else: return False
def main():
global k
# Initiate variables and sort the list
num_range = 40
num_numbers = 20
num_find = random.randint(1, num_range)
sorter = sorted_list(num_range, num_numbers)
# timer for checking speed
##start_time = time.time()
# Puts the list through a binary search and returns whether the number being searched for is present in the list
answer = binary_search(sorter, num_find)
# if the list is less then 10k numbers,
# then this is more efficient
#if num_find in sorter: answer = True
#else: answer = False
##print("--- %.7f seconds ---" % (time.time() - start_time))
if answer == True:
k += 1
return answer, num_find
def run():
i = 0
while i < 30:
print (main())
print('')
i += 1
print ('False {} times'.format(k))
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment