Is there a built-in function to do binary search? Say, given a list (sorted) and a number, find the position which keeps the listed sorted when the number is inserted.
I know that
LengthWhile could manage that, but it's slow.
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.Sign up to join this community
There is some built-in binary search code but not in the core language as far as I know.
BinarySearch from the Combinatorica package, which is still the function I use most often despite the fact that that package is now deprecated and loading it causes shadowing of some Symbols.
There is the undocumented
GeometricFunctions`BinarySearch but this function does not appear to perform particularly well.
When I need greater performance I typically use a compiled form of Leonid's code from: