Skip to content

Instantly share code, notes, and snippets.

@ffbit
Last active December 12, 2015 00:08
Show Gist options
  • Select an option

  • Save ffbit/4681847 to your computer and use it in GitHub Desktop.

Select an option

Save ffbit/4681847 to your computer and use it in GitHub Desktop.
Binary search with Ruby
def binary_search(a, needle)
start = 0
finish = a.size - 1
while start <= finish do
middle = start + (finish - start) / 2
if a[middle] == needle
return middle
elsif a[middle] < needle
start = middle + 1
else
finish = middle - 1
end
end
- (start + 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment