Created
April 19, 2010 19:46
-
-
Save akkartik/371501 to your computer and use it in GitHub Desktop.
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
# http://reprog.wordpress.com/2010/04/19/are-you-one-of-the-10-percent | |
A = [0, 34, 100] | |
def binary_search(i, j, v): | |
if j-i <= 2: | |
for k in range(i,j): | |
if A[k] == v: | |
return j | |
return -1 | |
# j > i+2 | |
mid = (i+j)/2 | |
if A[mid] == v: | |
return mid | |
if A[mid] > v: | |
return binary_search(i, mid, v) | |
if A[mid] < v: | |
return binary_search(mid, j, v) | |
binary_search(0, len(A), 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A = [1]
binary_search(0, len(A), 1) # returns 1, which is not even a valid index
Guess you're not part of the 10%