Skip to content

Instantly share code, notes, and snippets.

@emre
Created August 2, 2013 09:22
Show Gist options
  • Select an option

  • Save emre/6138594 to your computer and use it in GitHub Desktop.

Select an option

Save emre/6138594 to your computer and use it in GitHub Desktop.
binary search implementation
# -*- coding: utf8 -*-
def binary_search(l, value):
""" (list, object) -> int
>>> binary_search([1, 2, 3, 4, 5], 3)
2
>>> binary_search([1, 2, 3, 4, 5], 5)
4
>>> binary_search([1, 2, 3, 4, 5], 8)
-1
"""
start_index = 0
end_index = len(l) - 1
while(start_index <= end_index):
m = (start_index + end_index) // 2
if l[m] < value:
start_index = m + 1
else:
end_index = m - 1
if start_index == len(l) or l[start_index] != value:
return -1
else:
return start_index
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment