Skip to content

Instantly share code, notes, and snippets.

@msonnabaum
Created July 30, 2015 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msonnabaum/7b8d7b6f6959820b1207 to your computer and use it in GitHub Desktop.
Save msonnabaum/7b8d7b6f6959820b1207 to your computer and use it in GitHub Desktop.
def bsearch_index(ary)
low = 0
high = ary.length
smaller = 0
satisfied = 0
while low < high
mid = low + ((high - low) / 2)
val = ary[mid]
begin
v = yield val
rescue
val = ary[mid+1]
retry
end
if v == true
satisfied = 1
smaller = 1
elsif v == false || v == nil
smaller = 0
else
raise TypeError, "wrong argument type #{v.class} (must be numeric, true, false or nil)"
end
if smaller > 0
high = mid
else
low = mid + 1
end
end
return nil if low == ary.length
return nil unless satisfied
return low
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment