-
-
Save henrybear327/4646bcf68205517a10d9c1e9af183a6d to your computer and use it in GitHub Desktop.
cpp-like lower_bound, upper_bound in Ruby
This file contains hidden or 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 lowerBound(a, key) | |
lb = -1; ub = a.length | |
while ub - lb > 1 | |
mid = (lb + ub) / 2 | |
if a[mid] >= key | |
ub = mid | |
else | |
lb = mid | |
end | |
end | |
ub | |
end | |
def upperBound(a, key) | |
lb = -1; ub = a.length | |
while ub - lb > 1 | |
mid = (lb + ub) / 2 | |
if a[mid] <= key | |
lb = mid | |
else | |
ub = mid | |
end | |
end | |
ub | |
end |
This file contains hidden or 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 lowerBound(a, key) | |
idx = (0...a.size).bsearch { |i| a[i] >= key } | |
#idx = bsearch_index { |e| e >= key } #Ruby 2.3 and later | |
idx.nil? ? a.size : idx | |
end | |
def upperBound(a, key) | |
idx = (0...a.size).bsearch { |i| a[i] > key } | |
#idx = bsearch_index { |e| e > key } #Ruby 2.3 and later | |
idx.nil? ? a.size : idx | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment