Skip to content

Instantly share code, notes, and snippets.

@hunterbridges
Created October 14, 2011 06:27
Show Gist options
  • Save hunterbridges/1286393 to your computer and use it in GitHub Desktop.
Save hunterbridges/1286393 to your computer and use it in GitHub Desktop.
Binary search for michael
import math
def binary_search(needle, haystack):
search_index = int(math.floor(len(haystack) / 2))
test_item = haystack[search_index]
print "Searching for %d in %s" % (needle, haystack)
print "Haystack is %d long. First looking at index %d" % (len(haystack),
search_index)
print "Item at index %d is %d" % (search_index, haystack[search_index])
if (test_item != needle and len(haystack) == 1):
haystack.insert(search_index, needle)
return search_index
if (test_item == needle):
return search_index
if (test_item < needle):
return search_index + binary_search(needle, haystack[search_index:])
if (test_item > needle):
return binary_search(needle, haystack[:search_index])
haystack = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment