Skip to content

Instantly share code, notes, and snippets.

@reterVision
Created March 26, 2013 00:51
Show Gist options
  • Save reterVision/5242252 to your computer and use it in GitHub Desktop.
Save reterVision/5242252 to your computer and use it in GitHub Desktop.
Binary Search in Python
#!/usr/bin/python
"""
Binary Search
"""
def bsearch(array, min, max, target):
if max < min:
return -1
mid = (max + min) / 2
if array[mid] == target:
return mid
elif array[mid] > target:
return bsearch(array, min, mid-1, target)
elif array[mid] < target:
return bsearch(array, mid+1, max, target)
def main():
l = range(0, 10)
print l
result = bsearch(l, 0, len(l)-1, 9)
print 'Search for {0}, result: {1}'.format(9, result)
result = bsearch(l, 0, len(l)-1, 0)
print 'Search for {0}, result: {1}'.format(0, result)
result = bsearch(l, 0, len(l)-1, 6)
print 'Search for {0}, result: {1}'.format(6, result)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment