Skip to content

Instantly share code, notes, and snippets.

@PerroBueno
Created May 26, 2018 23:23
Show Gist options
  • Save PerroBueno/8b0a492864199834c3574a0322ade920 to your computer and use it in GitHub Desktop.
Save PerroBueno/8b0a492864199834c3574a0322ade920 to your computer and use it in GitHub Desktop.
binary search
import random
#Linear search
def linseach(ordered_list, element_to_find):
for i in ordered_list:
if i == element_to_find:
return True
return False
#Binary search
def binsearch(ordered_list, element_to_find):
end = len(ordered_list) - 1
mid = int((end / 2))
while mid != end:
end = len(ordered_list) - 1
mid = int((end / 2))
if element_to_find == ordered_list[mid]:
return True
else:
if element_to_find < ordered_list[mid]:
ordered_list = ordered_list[0:(mid+1)]
else:
ordered_list = ordered_list[(mid+1):(end+1)]
return False
#Returns True if num is in list, otherwise false.
list = sorted(random.sample(range(1,100), 50))
num = int(input("Enter a number "))
print(binsearch(list, num))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment