Skip to content

Instantly share code, notes, and snippets.

@jamesdaniels
Created April 19, 2010 20:15
Show Gist options
  • Save jamesdaniels/371534 to your computer and use it in GitHub Desktop.
Save jamesdaniels/371534 to your computer and use it in GitHub Desktop.
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
@newacct
Copy link

newacct commented Apr 26, 2011

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".

@jamesdaniels
Copy link
Author

Awesome catch, ty ty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment