Created
April 19, 2010 20:15
-
-
Save jamesdaniels/371534 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
def binary_search(list, match, index = 0) | |
if list.empty? | |
-1 | |
else | |
mid = list.length/2 | |
case list[mid] <=> match | |
when 0 | |
index + mid | |
when 1 | |
binary_search(list[0...mid], match, index) | |
when -1 | |
binary_search(list[mid+1..-1], match, index + mid + 1) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The range "mid+1..list.length" technically includes "list.length", which is not a valid index of "list". Although it does not hurt to include a range too big (values off the end will simply be ignored), it would be more accurate to use "...list.length", or "..list.length-1", or even simpler, "..-1".