sort
- arrayfire.sort(array: Array, /, axis: int = 0, is_ascending: bool = True, *, keys: None = None, is_index_array: Literal[False] = False) Array
- arrayfire.sort(array: Array, /, axis: int = 0, is_ascending: bool = True, *, keys: Array, is_index_array: Literal[False] = False) tuple[Array, Array]
- arrayfire.sort(array: Array, /, axis: int = 0, is_ascending: bool = True, *, keys: None = None, is_index_array: Literal[True]) tuple[Array, Array]
Sorts the elements of an ArrayFire array along a specified dimension. Optionally, sorting can be performed based on keys, or sorted indices can be returned.
Parameters
- arrayArray
The input multi-dimensional ArrayFire array to be sorted.
- axisint, default: 0
The dimension along which the sorting is to be performed.
- is_ascendingbool, default: True
Determines the direction of the sort. If True, the sorting is done in ascending order; otherwise, in descending order.
- keysArray, optional
An optional ArrayFire array containing keys based on which the sorting should be performed. If provided, the elements in array are sorted according to the order determined by these keys.
- is_index_arraybool, default: False
If True, the function returns a tuple of arrays - the sorted array and an array of indices that maps the sorted array back to the original array.
Returns
- Array | tuple[Array, Array]
If neither keys nor is_index_array is provided, returns the sorted array. If keys is provided, returns a tuple (sorted_keys, sorted_values) where sorted_keys is the keys sorted and sorted_values are the elements of array sorted according to sorted_keys. If is_index_array is true, returns a tuple (sorted_array, indices) where sorted_array is the sorted array and indices maps the sorted array back to the original array.
Raises
- RuntimeError
If both keys and is_index_array are provided.
Examples
>>> import arrayfire as af >>> a = af.randu(5) # Create a random 1D array >>> a [5 1 1 1] 0.6010 0.0278 0.9806 0.2126 0.0655
>>> af.sort(a) # Sort the array in ascending order [5 1 1 1] 0.0278 0.0655 0.2126 0.6010 0.9806
>>> keys = af.Array([3, 2, 1, 5, 4]) >>> values = af.Array([10, 20, 30, 40, 50]) >>> sorted_keys, sorted_values = af.sort(values, keys=keys) >>> sorted_keys [5 1 1 1] 1.0000 2.0000 3.0000 4.0000 5.0000
>>> sorted_values [5 1 1 1] 30.0000 20.0000 10.0000 50.0000 40.0000
>>> sorted_array, indices = af.sort(a, is_index_array=True) >>> sorted_array [5 1 1 1] 0.0278 0.0655 0.2126 0.6010 0.9806
>>> indices [5 1 1 1] 1 4 3 0 2
Note
The sorting based on keys (sort_by_key) or returning sorted indices (sort_index) cannot be performed simultaneously. Select only one option per function call.