NumPy: Sorting Arrays Using sort()

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

numpy.sort():

It is used to return a sorted copy of an 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.

Returns: 

It is used to return the sorted array.

Example:

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)

Output:

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.

kindspeedworst-caseworkspacestable
‘quicksort’1O(n^2)0no
'mergesort’2O(n*log(n))~n/2yes
‘heapsort’3O(n*log(n))nono