Even better: get rid of the brackets around 1:0.1:100000, and you'll be that much more impressed.
--Tim On Sunday, April 10, 2016 07:16:16 AM Fred wrote: > Hi, > > I post here my best solution taking advantage that the array is sorted. I > expected to be a lot much faster than other solutions, but not really. > I am very impressed by the speed of searchsorted > > > x = [1:0.1:1000000] > val = 8.22 > > function dicotomy(x, val) > a = start(eachindex(x)) > b = length(x) > j = length(x) > dxbest = abs(x[a]-val) > dx = dxbest > > while true > dx < dxbest ? dxbest = dx : 1 > j = round(Int,(a+b)/2) > dx = x[j]-val > x[j]-val < 0 ? a = j : b = j > abs(a-b) < 2 && break > end > return a,b > end > > @time dicotomy(x, 8.22) > 0.000004 seconds (5 allocations: 192 bytes) > (73,74) > > > @time searchsorted(x, 8.22) > 0.000005 seconds (7 allocations: 240 bytes) > > @time closest_index(x,8.22) > 0.027618 seconds (4 allocations: 160 bytes) > 73
