NumPy sort()

The sort() method sorts an array in ascending order.


sort() Syntax

The syntax of sort() is:

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

sort() Arguments

The sort() method takes four arguments:

  • array - array to be sorted
  • axis (optional) - axis along which the values are appended
  • order (optional) - field to be compared
  • kind (optional) - sorting algorithm

Notes:

  • By default, axis is -1, the array is sorted on the basis of the last axis.
  • kind can be quicksort (default), mergesort, or heapsort.

sort() Return Value

The sort() method returns a sorted array.


Example 1: Sort a Numerical Array

Output

[-1.4  2.1  9.9 10.2]

Example 2: Sort a String Array

Output

['Apple' 'Ball' 'Cat' 'apple']

Example 3: Sort a Multidimensional Array

Multidimensional arrays are sorted based on the given axis.

Output

Sorted based on last axis(1) : 
[[ 2  3 10]
 [ 1  5  7]
 [ 2  5  7]]

Sorted a flattened array [ 1  2  2  3  5  5  7  7 10]

Sorted based on axis 0 : 
 [[ 1  5  2]
 [ 2  7  5]
 [ 3 10  7]]

When sorting based on axis 0, rows are compared. The elements in the first column are sorted first followed by the second column and so on. All columns are sorted independently of each other.


Example 4: Sort an Array With order Argument

Output

[('Alice', 25, 170) ('Charlie', 35, 175) ('Bob', 30, 180)]

Example 5: Sort an Array With Multiple order Argument

Output

[('Alice', 25, 170) ('Charlie', 35, 175) ('Dan', 40, 175) ('Eeyore', 25, 180) ('Bob', 30, 180)]

The kind Argument

The kind argument is used in NumPy sort() to specify the algorithm used for sorting. For example,

The kind argument can take several values, including,

  • quicksort (default): This is a fast algorithm that works well for most cases i.e. small and medium-sized arrays with random or uniformly distributed elements.
  • mergesort: This is a stable, recursive algorithm that works well for larger arrays with repeated elements.
  • heapsort: This is a slower, but guaranteed O(n log n) sorting algorithm that works well for smaller arrays with random or uniformly distributed elements

The kind argument has no direct impact on the output but it determines the performance of the method.