Nearest binary search04 Sep 2022 by Friedrich Ewald · 2 min read
To find the exact element or the next element that is greater than the target, use the following code. This algorithm returns an invalid index if the element that is searched for is greater than the greatest element in the array. This needs to be manually checked with
s(items, target) == len(items).
If you want to find the element which is exactly the element or less than the element, change the return value to
return m - 1 instead. In the smallest case this will return
-1 which means that the element searched for is smaller than the smallest on in the list. The resulting code looks like this: