Created
July 30, 2015 22:00
-
-
Save msonnabaum/7b8d7b6f6959820b1207 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 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