Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Find the position of a target value within a sorted array
ResourceFunction["BinarySearch"][v,val] gives the position of the last element of a sorted numeric vector v such that the element ei≤val. |
Find the position of the last element that is not greater than 6 in a list of numbers in ascending order:
In[1]:= |
Out[1]= |
BinarySearch[v,val] returns 0 when all elements of v are greater than the val:
In[2]:= |
Out[2]= |
BinarySearch can be considerably faster for packed arrays:
In[3]:= |
In[4]:= |
Out[4]= |
In[5]:= |
Out[5]= |
In[6]:= |
In[7]:= |
Out[7]= |
BinarySearch can give an erroneous result if the input vector is not sorted:
In[8]:= |
Out[8]= |
Use LengthWhile to find the position of first element less than 1 in an unsorted list:
In[9]:= |
Out[9]= |
This work is licensed under a Creative Commons Attribution 4.0 International License