# NumPy Search Sort

In this tutorial you will learn:

• NumPy searchsorted function()
• How to use NumPy searchsorted?
• Python syntax

NumPy searchsorted() function

NumPy searchsorted() function works well for the sorted arrays as this algorithm specifies the index into which the number should be inserted inorder to maintain a sequence and search order of the array. The seachsorted() alogirthm performs a binary search as it compares the target value to the middle element of the array and progresses accordingly.

Examples

In order to enhance the understanding of this algorithm lets take an example. In this example we will find the correct index for number ‘5’ in order to keep the array in an ascending order.

`import numpy as npmy_arr = np.array([1,2,3,4,6,7,8,9,10])print('Array being searched is:', my_arr)#applying sorted searchres = np.searchsorted(my_arr,5)print('\n The indexes at which the number should be placed at:\n',res)`

The searchsorted() function works irrespective of the data types. Lets take an example, in this example we are finding the correct index for placement of a character ‘c’.

`import numpy as npmy_arr = np.array(['a','b','d','e'])print('Array being searched is:', my_arr)#applying sorted searchres = np.searchsorted(my_arr,'c')print('\n The indexes at which the character should be placed at:\n',res)`

The searchsorted() function can also take in third parameter “side” related to the direction of search, we can either define it as “left” or “right”.

In this example we will first carry out left search and then we will carry out right search. In results you can observe that the result returned by both the searches is same. The left search starts from index 0 while the right search start from index -1. The searchsorted() function starts search from either left or right side and outputs the index of number lesser or greater than the number being searched depending upon the “side” parameter if its left or right.

`import numpy as npmy_arr = np.array([1,2,3,4,5,6,7,8,10])print('Array being searched is:', my_arr)#applying right sorted searchres1 = np.searchsorted(my_arr,9,side='right')#applying right sorted searchres2 = np.searchsorted(my_arr,9,side='left')print('\n The indexes at which the number should be placed at(right sorting):\n',res1)print('\n The indexes at which the number should be placed at(left sorting):\n',res2)`

### Tags

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.