Re: Efficient search for bounding list elements

*To*: mathgroup at smc.vnet.net*Subject*: [mg114169] Re: Efficient search for bounding list elements*From*: Bob Hanlon <hanlonr at cox.net>*Date*: Fri, 26 Nov 2010 05:26:47 -0500 (EST)

boundsPositions[a_List, x_] := Module[{n = 0}, If[x < a[[1]], {"Unbounded", 1}, If[x > a[[-1]], {Length[a], "Unbounded"}, Catch[(n++; If[# > x, Throw[{n - 1, n}]]) & /@ a]]]] a = Range[1000, 5000, 250]; boundsPositions[a, #] & /@ {500, 1600, 6000} {{"Unbounded", 1}, {3, 4}, {17, "Unbounded"}} Bob Hanlon ---- David Skulsky <edskulsky at gmail.com> wrote: ============= I've been looking for a way to efficiently find the indices of the two elements of a monotonically increasing list which bound a number. For example, if a = Range[1000,5000,250] and x=1600 then I'd like this function (e.g., searchFunction[x,a]) to return {3,4}, which correspond to the 3rd and 4th elements of a, which are 1500 and 1750, respectively. I can easily do this in a loop, but in my application a can be very large (hundreds of thousands or millions of elements) and this operation needs to repeated thousands of times, so efficiency is critical. Any suggestions would be greatly appreciated! Thanks, David Skulsky