This is a pre-release version (latest). Go to latest (2.4.4)
{ } Raw JSON

bundles / numpy latest / numpy / sort

_ArrayFunctionDispatcher

numpy:sort

source: /dev/numpy/build-install/usr/lib/python3.14/site-packages/numpy/_core/fromnumeric.py :939

Signature

def   sort ( a axis = -1 kind = None order = None * stable = None )

Summary

Return a sorted copy of an array.

Parameters

a : array_like

Array to be sorted.

axis : int or None, optional

Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.

kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional

Sorting algorithm. The default is 'quicksort'. Note that both 'stable' and 'mergesort' use timsort or radix sort under the covers and, in general, the actual implementation will vary with data type. The 'mergesort' option is retained for backwards compatibility.

order : str or list of str, optional

When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

stable : bool, optional

Sort stability. If True, the returned array will maintain the relative order of a values which compare as equal. If False or None, this is not guaranteed. Internally, this option selects kind='stable'. Default: None.

Returns

sorted_array : ndarray

Array of the same type and shape as a.

Notes

The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The four algorithms implemented in NumPy have the following properties:

=========== ======= ============= ============ ========
   kind      speed   worst case    work space   stable
=========== ======= ============= ============ ========
'quicksort'    1     O(n^2)            0          no
'heapsort'     3     O(n*log(n))       0          no
'mergesort'    2     O(n*log(n))      ~n/2        yes
'timsort'      2     O(n*log(n))      ~n/2        yes
=========== ======= ============= ============ ========

For performance, sort makes a temporary copy if needed to make the data contiguous in memory along the sort axis. For even better performance and reduced memory consumption, ensure that the array is already contiguous along the sort axis.

The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts.

Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is:

  • Real: [R, nan]

  • Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]

where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before.

quicksort has been changed to: introsort. When sorting does not make enough progress it switches to heapsort. This implementation makes quicksort O(n*log(n)) in the worst case.

'stable' automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with 'mergesort' is currently mapped to timsort or radix sort depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types.

Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen. For timsort details, refer to CPython listsort.txt 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an O(n) sort instead of O(n log n).

NaT now sorts to the end of arrays for consistency with NaN.

Examples

import numpy as np
a = np.array([[1,4],[3,1]])
np.sort(a)                # sort along the last axis
np.sort(a, axis=None)     # sort the flattened array
np.sort(a, axis=0)        # sort along the first axis
Use the `order` keyword to specify a field to use when sorting a structured array:
dtype = [('name', 'S10'), ('height', float), ('age', int)]
values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
          ('Galahad', 1.7, 38)]
a = np.array(values, dtype=dtype)       # create a structured array
Sort by age, then height if ages are equal:

See also

argsort

Indirect sort.

lexsort

Indirect stable sort on multiple keys.

ndarray.sort

Method to sort an array in-place.

partition

Partial sort.

searchsorted

Find elements in a sorted array.

Aliases

  • numpy.sort

Referenced by