Skip to main content

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
Submitted by devanshi.srivastava on September 7, 2021

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


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.