Last active
August 7, 2016 19:57
-
-
Save rtacconi/7b4387e3e02bee4c4594dfdc2d002099 to your computer and use it in GitHub Desktop.
Binary search
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
def binary_search(list, item) | |
low = 0 | |
high = list.size - 1 | |
return nil if list.last < item # item not in array | |
while low < high do | |
mid = (low + high) / 2 | |
guess = list[mid] | |
if guess == item | |
return mid | |
elsif guess > item | |
high = mid - 1 | |
else | |
high = mid + 1 | |
end | |
end | |
# while terminated without finding anything | |
return nil | |
end | |
p binary_search([1,3,4,6,100], 4) | |
p binary_search([1,3,4,6,100], 400) | |
p binary_search(['f', 'g', 'h', 'i'], 'h') | |
p binary_search(['fa', 'ga', 'ha', 'ia'], 'ia') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment