Sorting and Searching techniques are two most crucial things to learn in Data Structure and Algorithms. We can sort an array or list using some predefined functions available in Python. Python Sorting and Searching is really easy compared to other programming as You just need to apply these methods.
I hope you have already tried once using normal logic before jumping to this blog as that will make your concept clear and this will make your work easier. Enjoy the blog now.
Sorting an array using sort() function
Sorting an array using msort() function
Sorting an array using lexsort() function
Sorting an array using argsort() function
Sorting an array using numpy.ndarray.sort() function
Search Sorted Method
Sorting an array using sort() function:
Sorting is the process where we try to put element in their order of sequence. It can be ascending or descending as per the user requirements.
numpy.sort(): This method will return a sorted copy of array.
Syntax:
numpy.sort(a, axis=- 1, kind=None, order=None)
Parameters:
- a- Array to be sorted.
- Axis-Axis along which array is to be sorted.
- kind-Sorting algorithm[‘quicksort’, ‘mergesort’, ‘heapsort’].
- The default value is set to 'quicksort'.
- order-This specify which field is to compare first.
It is used to return a sorted array.
import numpy as np
# sorting along the first axis
arr = np.array([[1,3,4],
[5,8,7],
[4,3,6]])
arr_sort = np.sort(arr,axis = 0) #Along first axis
print(arr_sort)
print("\n")
arr_sort = np.sort(arr, axis = -1) #Along first axis
print(arr_sort)
print("\n")
arr_sort = np.sort(arr, axis = None)
print(arr)
Output:
[[1 3 4]
[4 3 6]
[5 8 7]]
[[1 3 4]
[5 7 8]
[3 4 6]]
[[1 3 4]
[5 8 7]
[4 3 6]]
Sorting an arrays using msort() function:
It is used to return a copy of an array sorted along the first axis. It is same as numpy.sort() along the axis=0
Syntax:
numpy.msort(a)
import numpy as np
arr = np.array([1,9,5,8,6])
np.msort(arr)
Output:
[1 9 5 8 6]
Sorting an arrays using argsort() function:
It is used to return the indices that would sort an array. It performs an indirect sorting along the specified axis and kind keyword. It returns an array of indices of the same shape as that index data along the given axis in sorted order.
Syntax:
numpy.argsort(a, axis=- 1, kind=None, order=None)
Parameters:
axis: int or None, optional
The default is -1 (the last axis). If None, the flattened
array is used.kind: {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional
Sorting algorithm. The default is ‘quicksort’. Note that
both ‘stable’ and ‘mergesort’ use timsort under the covers
and, in general, the actual implementation will vary with
data type. The ‘mergesort’ option is retained for backwards
compatibility.order: str or list of str, optional
import numpy as np
arr=np.array([40,50,20,70,60,10])
arra_sort=np.argsort(arr,axis=0)
#It is used to returns the indices that would sort an array.
print(arra_sort)
print("\n")
x = np.array([[0, 3], [2, 2]])
x_sort = np.argsort(x, axis=0)
print(x_sort)
Ouput:
[5 2 0 1 4 3]
[[0 1]
[1 0]]
Sorting an arrays using lexsort() function:
It is used to perform indirect sorting using a sequence of keys.
If multiple sorting keys can be interpreted as columns in a spreadsheet. Here, we can use lexsort() which returns an array of integer indices that describe the sorted order of multiple columns.
lexsort((B,A))
In this method, the last key (A-here) in the sequence is used as the primary sorting order and the second-to-last key(B-here) for secondary sort order and so on.
Syntax:
numpy.lexsort(keys, axis=- 1)
A= np.array([10,15,10,14,13,14]) # First column
B= np.array(['b','d','a','d','c','f']) # Second column
result= np.lexsort((B,A)) # Sort by a, then by b
print(result)
Output:
[2 0 4 3 5 1]
We are sorting here a as per b. Now first 10 is minimum in a-array but 10 is there in index 0 and in index 2. So, now refer array-b and check for those 2 position which one is coming first. As value a is lesser than value b. So, in sorted array index 2 will come first then index 0 and so on.
Sorting an arrays using numpy.ndarray.sort() function:
Sort an array in-place. Its little bit same as we did in np.sort(axis=- 1, kind=None, order=None). Please refer to the first point where i have explained it everything. Here we are just taking numpy as a whole module. Else you can do it using alias name np.sort().
Syntax:
ndarray.sort(axis=-1, kind='quicksort', order=None)
a = np.array([[1,4], [3,1]])
a.sort(axis=1)
print(a)
Output:
array([[1, 4],
[1, 3]])
Search Sorted Method in Numpy:
This is mainly used to search the indices into the sorted array such that, suppose if the elements in the array are inserted before the indices, the order of that array is still preserved.
It returns indices. It is the array of insertion points with the same shape as that of number.
Syntax:
numpy.serachsorted( arr, num, side='left',sorter=None)
Parameters:
- arr: The given array. If the given sorter is None, then the array must be sorted in ascending order, otherwise, the sorter must be used in an array for sorting it.
- num: Values which we will insert into the given array.
- side: {‘left’, ‘right’}, It is optional. If the side is 'left', the index of the first suitable location found will be given. If the side is 'right', it will return the last such index. If there is no suitable index it will return 0 or N.(where N is the length of the input array)
- sorter: It is also optional. It is the array of integer indices that sort the array into ascending order. It is the result of argsort.
import numpy as np
array_1=[2,3,4,5,6,7]
num=10
res_array=np.searchsorted(array_1,num)
print(res_array)
Output:
6
These are different types of sorting and searching method present in Numpy.
If you want to learn everything basics about Numpy. Please visit the below link. If you like this please give it a star.
Follow me on Github for more programs and projects related to Python.
Github
Thanks Guys for reading this!
Top comments (0)