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.

  1. import numpy as np
  2. my_arr = np.array([1,2,3,4,6,7,8,9,10])
  3. print('Array being searched is:', my_arr)
  4. #applying sorted search
  5. res = np.searchsorted(my_arr,5)
  6. 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’.

  1. import numpy as np
  2. my_arr = np.array(['a','b','d','e'])
  3. print('Array being searched is:', my_arr)
  4. #applying sorted search
  5. res = np.searchsorted(my_arr,'c')
  6. 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.

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

Add new comment