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]:= | ![ResourceFunction["BinarySearch"][{1, 2, 5, 5, 7, 12}, 6]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/30eeb10bc3355b5e.png) | 
| Out[1]= |  | 
BinarySearch[v,val] returns 0 when all elements of v are greater than the val:
| In[2]:= | ![ResourceFunction["BinarySearch"][{1, 1, 2}, -1]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/14d5dd1ccfd31fdc.png) | 
| Out[2]= |  | 
BinarySearch can be considerably faster for packed arrays:
| In[3]:= | ![packed = Sort[RandomReal[{0, 100}, 100000]];](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/753383fbd4277349.png) | 
| In[4]:= | ![RepeatedTiming[ResourceFunction["BinarySearch"][packed, 50]]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/5dfd2a7e70a3cb9a.png) | 
| Out[4]= |  | 
| In[5]:= | ![Developer`PackedArrayQ[packed]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/44e7197c4566e466.png) | 
| Out[5]= |  | 
| In[6]:= | ![unpacked = Developer`FromPackedArray[packed];](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/71cefee53601f67b.png) | 
| In[7]:= | ![RepeatedTiming[ResourceFunction["BinarySearch"][unpacked, 50]]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/4f3924e66b848054.png) | 
| Out[7]= |  | 
BinarySearch can give an erroneous result if the input vector is not sorted:
| In[8]:= | ![ResourceFunction["BinarySearch"][{0, 2, 0}, 1]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/41beb591a0591115.png) | 
| Out[8]= |  | 
Use LengthWhile to find the position of first element less than 1 in an unsorted list:
| In[9]:= | ![LengthWhile[{0, 2, 0}, # < 1 &]](https://www.wolframcloud.com/obj/resourcesystem/images/c8a/c8a94793-1a70-48f7-bbcd-ecf157b7a237/2485bebd6be46800.png) | 
| Out[9]= |  | 
This work is licensed under a Creative Commons Attribution 4.0 International License