sortperm!

..  sortperm!(ix, v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false,] [initialized=false])

Like ``sortperm``, but accepts a preallocated index vector ``ix``.  If ``initialized`` is ``false``
(the default), ix is initialized to contain the values ``1:length(v)``.

See also :func:`sortperm`

Examples

The sortperm! function in Julia is used to obtain the permutation vector that would sort a given array, and store the result in a preallocated index vector ix. The sortperm! function allows customization through optional arguments such as the sorting algorithm, transformation function, comparison function, reverse ordering, and initialization.

Here are some examples of how to use the sortperm! function:

  1. Sort an array and obtain the permutation vector:

    julia> arr = [4, 1, 3, 2];
    julia> ix = similar(arr);
    julia> sortperm!(ix, arr)
    4-element Array{Int64,1}:
    2
    4
    3
    1

    In this example, the sortperm! function is used to sort the array arr and store the resulting permutation vector in the preallocated index vector ix.

  2. Sort an array in reverse order and obtain the permutation vector:

    julia> arr = [4, 1, 3, 2];
    julia> ix = similar(arr);
    julia> sortperm!(ix, arr, rev=true)
    4-element Array{Int64,1}:
    1
    3
    4
    2

    By setting the rev argument to true, the sortperm! function sorts the array arr in reverse order and returns the corresponding permutation vector.

  3. Sort an array using a custom comparison function:
    julia> arr = [4, 1, 3, 2];
    julia> ix = similar(arr);
    julia> sortperm!(ix, arr, lt=>)
    4-element Array{Int64,1}:
    1
    3
    4
    2

    In this example, the lt argument is set to > to specify that the array arr should be sorted in descending order.

Common mistake example:

julia> arr = [4, 1, 3, 2];
julia> ix = similar(arr)[2:end];
julia> sortperm!(ix, arr)
ERROR: BoundsError: attempt to access 3-element Array{Int64,1} at index [4]

Here, the ix vector is not properly preallocated, resulting in a bounds error. Ensure that the ix vector has the same length as the array being sorted or use similar(arr) to allocate an index vector with the same size as arr before calling sortperm!.

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.

*Required Field
Details

Checking you are not a robot: