NumPy: Sorting Arrays Using sort()

Sorting is the process in which we try to put elements in an ordered sequence.


It is used to return a sorted copy of an array.


numpy.sort(a, axis=- 1, kind=None, order=None)


  • 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 the sorted array.


import numpy as np
# sorting along the first axis
a = np.array([[1,7,4],[2,8,5],[9,3,6]])
b=np.sort(a, axis = 0)        
print ("Along first axis-",b)  
#sorting along last axis
c=np.sort(a, axis = -1)        
print("Along first axis-",c)
#sorting in 1-D array
d=np.sort(a, axis = None)        
print("Along none axis-",d)


Along first axis- [[1 3 4]
 [2 7 5]
 [9 8 6]]
Along first axis- [[1 4 7]
 [2 5 8]
 [3 6 9]]
Along none axis- [1 2 3 4 5 6 7 8 9]

Note: As we know, that there are various types of sorting algorithms that are characterised by their worst-case performance, workspace size, average speed whether they are stable or not. A stable sort is used to keeps items with the same key in the same relative order.

kind speed worst-case workspace stable
‘quicksort’ 1 O(n^2) 0 no
'mergesort’ 2 O(n*log(n)) ~n/2 yes
‘heapsort’ 3 O(n*log(n)) no no
Tue, 09/07/2021 - 15:45

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.