I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that
np.searchsorted
is binary search (split the array in half each time). So you have to implement it in a way it return the last value smaller than x instead of returning zero.
Look at this algorithm (from here):
def binary_search(a, x):
lo=0
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
midval = a[mid]
if midval < x:
lo = mid+1
elif midval > x:
hi = mid
else:
return mid
return lo-1 if lo > 0 else 0
just replaced the last line (was return -1
). Also changed the arguments.
As the loops are written in Python, it may be slower than the first one... (Not benchmarked)