I had to use something like
arr = [10, 20, 50, 80, 110]
(arr.bsearch_index{|a| a >= 50} || arr.length) - 1 # => 1
(arr.bsearch_index{|a| a >= 2000} || arr.length) - 1 # => 4
with the return value -1
meaning there is no such index. What if the numbers could be float, so you cannot look for 49
instead when n
is 50
. The code right now is a little bit messy. Is there a more elegant way to do it?
(Maybe it is just how bsearch_index()
does it: to return nil
when not found... so we just have to use bsearch(){ } || arr.length
to convert it back to strictly numbers -- so that's just the way it is. bsearch_index
has to either return only numbers or it can return nil
as a design decision and it chose to return nil
. But I am not sure if we just have to use the code above. Maybe the find-any
mode of bsearch_index
or some kind of way can do it and is more elegant.)
P.S. it might be interesting to use a reverse() operation or negating every element or something, but since those are O(n), it defeats the purpose of using a O(lg n) solution using binary search and we can just do a linear search.