Abstract
Sorts the array by the given axis, algorithm, and order. Note that there is a difference between the sort function and the sort method:
- function
- Returns a copy that is then sorted.
- method
Returns None, and sorts the array in-place.
Function
Method
Property
Signature
- Function
sort (arr, axis=-1, kind='quick', order=None)
- Method
arr.sort (axis=-1, kind='quick', order=None)
Returns
- Function
A sorted copy of arr.
- Method
- None. The sort is in-place and therefore affects the underlying array (no copy is made).
Arguments
- arr
- Array to be sorted.
- axis
- The axis the sort is applied to in a multi-dimensional array.
- kind
The underlying algorithm to use. Also see: algorithms
- 'quick'
- 'heap'
- 'merge'
- order
- Used for arrays with fields defined. Can be one of the following:
- A single string.
- Indicates that field as the basis for the sort.
- A list or tuple of strings.
- Basis is in list order.
- None
- If fields are defined, then the first field is the basis.
- A single string.
Details
algorithms
- The various sorts are characterized by average speed, worst case performance, need for work space, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The three available algorithms have the following properties:
kind
speed
worst case
work space
stable
quicksort
1
O(n^2)
0
no
mergesort
2
O(n*log(n))
~n/2
yes
heapsort
3
O(n*log(n))
0
no
Example
sort()
In [1]: from numpy import *
In [2]: a = array([2,0,8,4,1])
In [3]: a.sort() # in-place sorting with quicksort (default)
In [4]: a
Out[4]: array([0, 1, 2, 4, 8])
In [5]: a.sort(kind='mergesort') # algorithm options are 'quicksort', 'mergesort' and 'heapsort'
In [6]: a = array([[8,4,1],[2,0,9]])
In [7]: a.sort(axis=0)
In [8]: a
Out[8]:
array([[2, 0, 1],
[8, 4, 9]])
In [9]: a = array([[8,4,1],[2,0,9]])
In [10]: a.sort(axis=1) # default axis = -1
In [11]: a
Out[11]:
array([[1, 4, 8],
[0, 2, 9]])
In [12]: sort(a) # there is a functional form
Out[12]:
array([[1, 4, 8],
[0, 2, 9]])
Notes
Docs in the source for the function are incorrect:
sort(a, axis=-1, kind='quicksort', order=None)
Return copy of 'a' sorted along the given axis.
Perform an inplace sort along the given axis using the algorithm
specified by the kind keyword.It should only say it returns a copy that is sorted. It does not have any side effect of sorting the underlying array in-place.
See Also
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find keys in sorted array.