Skip to content

Instantly share code, notes, and snippets.

@vividhsv
Last active December 21, 2016 20:22
Show Gist options
  • Save vividhsv/25e71b2449bc226e528d45850132032a to your computer and use it in GitHub Desktop.
Save vividhsv/25e71b2449bc226e528d45850132032a to your computer and use it in GitHub Desktop.
Binary Search The binary search is used to find an item in an ORDERED list.
def binary_search(item, arr):
def _binary_search(item, first, last, arr):
if last < first:
return False
if last == first:
return arr[last] == item
mid = (first + last) // 2
if arr[mid] > item:
last = mid
return _binary_search(item, first, last, arr)
elif arr[mid] < item:
first = mid + 1
return _binary_search(item, first, last, arr)
else:
return arr[mid] == item
return _binary_search(item, 0, len(arr) - 1, arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment