Home > Net >  Built-in binary search algorithm in numpy that is like np.searchsorted?
Built-in binary search algorithm in numpy that is like np.searchsorted?

Time:11-13

I have a main numpy array a and I have another numpy array b. What I want to do is go through each element of b and check if that element exists in a. Keep in mind that both a and b are pretty massive, so I would like to avoid O(N) search times.

I know np.searchsorted(a,b) exists, but this provides an index at which I need to place b. This does not tell me if an element of b is present in a right off the bat.

My question is, is there a binary search algorithm built into numpy that simply reports True or False if an element from b exists in a? I am aware that I can write one but if there is a vectorized that is readily available, I could save some time.

Any advice would be appreciated!

CodePudding user response:

Once you have completed the sorted search you can check if the elements at those indices are equal to the elements in b:

a = numpy.array([1,2,3,4,7])
b = numpy.array([1,4,5,7])
x = numpy.searchsorted(a,b)
boolean_array = a[x] == b

searchsorted indicates that with the default side = 'left' it ensures : a[i-1] < v <= a[i] so if a[i] is equal to the corresponding element in b then it gives the match you want.

  • Related