binary_search

Definition: integer res = binary_search(object needle, sequence haystack)
Description: Finds a needle in an ordered haystack.

needle: an object to look for
haystack: an ordered sequence to be searched

Returns either a positive integer index, which means haystack[res]==needle, otherwise the negative index of where it would go if it were inserted now.

Results are undefined if haystack is not in ascending order or contains duplicates. In the latter case (ie ascending order with duplicates) it is guaranteed to locate one of the duplicates, but it could be the first, last, or anything inbetween.
Example:
?binary_search(0,{1,3,5})   -- -1
?binary_search(1,{1,3,5})   --  1
?binary_search(2,{1,3,5})   -- -2
?binary_search(3,{1,3,5})   --  2
?binary_search(4,{1,3,5})   -- -3
?binary_search(5,{1,3,5})   --  3
?binary_search(6,{1,3,5})   -- -4
See Also: find