What is sort() in NumPy?

In Python, the NumPy library has a function called sort(), which computes the sorting of an array. It returns a sorted copy of the array along the given axis of the same shape as the input array, in sorted order.

Syntax

numpy.sort(array, axis, kind, order)

Parameters

  • array (array_like): This specifies the array we want to sort.

  • axis (int or None), optional: This specifies the axis along which we want to sort. Default value is -1 specifying the last used axis. To use a flattened array, None is used.

  • kind (quicksort, mergesort, heapsort, stable), optional: This specifies the sorting algorithm to be used. The default value is “quicksort”.

  • order (str or list of str), optional: This specifies the order in which to compare fields.

Return value

  • ndarray: This returns a sorted array of the same type and shape, according the the specified parameters.

Example

#importing numpy libarary
import numpy as np
#initializing input numpy array
array1 = np.array([[ 4, 6, 2], [ 5, 1, 3]])
#computing merge sort
result1 = np.sort(array1, kind ='mergesort', axis = 0)
print ("merge sort", result1)
#computing heapsort
result2 = np.sort(array1, kind ='heapsort', axis = 1)
print ("heap sort", result2)
#computing quicksort
result3 = np.sort(array1, kind ='quicksort', axis = 1)
print ("quick sort", result3)

Free Resources