Skip to content

Instantly share code, notes, and snippets.

@digitalashes
Created November 28, 2017 08:37
Show Gist options
  • Save digitalashes/a774d037cbb246636ce3d7fa608c319e to your computer and use it in GitHub Desktop.
Save digitalashes/a774d037cbb246636ce3d7fa608c319e to your computer and use it in GitHub Desktop.
Binary Search in Python
# iterative implementation of binary search in Python
def binary_search(a_list, item):
"""Performs iterative binary search to find the position of an integer in a given, sorted, list.
a_list -- sorted list of integers
item -- integer you are searching for the position of
"""
first = 0
last = len(a_list) - 1
while first <= last:
i = (first + last) / 2
if a_list[i] == item:
return '{item} found at position {i}'.format(item=item, i=i)
elif a_list[i] > item:
last = i - 1
elif a_list[i] < item:
first = i + 1
else:
return '{item} not found in the list'.format(item=item)
# recursive implementation of binary search in Python
def binary_search_recursive(a_list, item):
"""Performs recursive binary search of an integer in a given, sorted, list.
a_list -- sorted list of integers
item -- integer you are searching for the position of
"""
first = 0
last = len(a_list) - 1
if len(a_list) == 0:
return '{item} was not found in the list'.format(item=item)
else:
i = (first + last) // 2
if item == a_list[i]:
return '{item} found'.format(item=item)
else:
if a_list[i] < item:
return binary_search_recursive(a_list[i+1:], item)
else:
return binary_search_recursive(a_list[:i], item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment