Created
October 14, 2011 06:27
-
-
Save hunterbridges/1286393 to your computer and use it in GitHub Desktop.
Binary search for michael
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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