Skip to content

Instantly share code, notes, and snippets.

@uncompiled
Last active September 5, 2017 16:34
Show Gist options
  • Save uncompiled/3367e807540ca18cee4af95575b13282 to your computer and use it in GitHub Desktop.
Save uncompiled/3367e807540ca18cee4af95575b13282 to your computer and use it in GitHub Desktop.
Binary Search Algorithm (Recursive)
def binary_search(ordered_list, search_item):
# If the length of the list is zero, it's empty,
# so the search_item can't be in the list.
if len(ordered_list) == 0:
return False
# Otherwise, let's try to find the item...
else:
middle_item = len(ordered_list) // 2
if search_item == ordered_list[middle_item]:
return True
elif search_item < ordered_list[middle_item]:
# The item we're looking for is smaller than the item in the middle.
#
# For example:
# We're looking for a 5, but the item in middle of the list is 7.
# We should throw out the second half of the list because we know
# everything in that half is larger than 7.
#
# Continue searching the first half of the list,
# which is everything from the beginning up to the middle item.
return binary_search(ordered_list[:middle_item], search_item)
elif search_item > ordered_list[middle_item]:
# The item we're looking for is larger than the item in the middle.
#
# For example:
# We're looking for a 7, but the item in the middle of the list is 5.
# We should throw out the first half of the list because we know
# everything in that half is smaller than 5.
#
# Continue searching the second half of the list.
# Start at middle_item + 1 because we already looked at middle_item.
return binary_search(ordered_list[middle_item + 1:], search_item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment