sortperm
.. sortperm(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])
Return a permutation vector of indices of ``v`` that puts it in sorted order.
Specify ``alg`` to choose a particular sorting algorithm (see Sorting Algorithms).
``MergeSort`` is used by default, and since it is stable, the resulting permutation
will be the lexicographically first one that puts the input array into sorted order –
i.e. indices of equal elements appear in ascending order. If you choose a non-stable
sorting algorithm such as ``QuickSort``, a different permutation that puts the array
into order may be returned. The order is specified using the same keywords as ``sort!``.
See also :func:`sortperm!`
Examples
The sortperm
function in Julia returns a permutation vector of indices that will sort the input array in ascending order. It can be used with various optional arguments to specify the sorting algorithm, transformation, comparison, and the order of sorting.
julia> v = [3, 1, 4, 2];
julia> sortperm(v)
4-element Array{Int64,1}:
2
4
1
3
In the above example, the sortperm
function returns the permutation vector [2, 4, 1, 3]
which represents the indices that would sort the array v
in ascending order.
Here are some additional examples:
-
Sort an array using a different algorithm:
julia> v = [3, 1, 4, 2]; julia> sortperm(v, alg=QuickSort) 4-element Array{Int64,1}: 2 4 1 3
The
sortperm
function allows specifying a particular sorting algorithm. Here,alg=QuickSort
is used to perform the sorting. -
Sort an array in descending order:
julia> v = [3, 1, 4, 2]; julia> sortperm(v, rev=true) 4-element Array{Int64,1}: 3 1 4 2
By setting
rev=true
, thesortperm
function sorts the array in descending order. - Sort an array based on a transformation:
julia> v = ["apple", "banana", "orange"]; julia> sortperm(v, by=length) 3-element Array{Int64,1}: 1 3 2
The
sortperm
function can accept a transformation function using theby
argument. Here, the arrayv
is sorted based on the length of its elements.
Please note that the sortperm
function is similar to sort!
, but it returns the permutation vector instead of modifying the input array in-place.
For more information, you can refer to the Julia Documentation on sortperm
and its related functions.
See Also
find, findfirst, findin, findlast, findmin, findn, findnext, findnz, findprev, rsearch, rsearchindex, searchsorted, searchsortedfirst, searchsortedlast, sort, sort!, sortcols, sortperm, sortperm!,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.