Qu

sortperm

Builtin index · Collections & strings

sortperm(x, [desc])

Input: x, desc · Output: no output

What it is

The 0-based indices that sort x, so x[sortperm(x)] is sorted. x is a numeric vector or a list of strings (byte order); desc is true or false (default false). The sort is stable in both directions: equal elements keep their original order, so sortperm([3, 1, 2, 1], true) is [0, 2, 1, 3]. NaN counts as the largest value (last ascending, first descending) and 0 equals -0. This differs from argsort(x, true), which reverses the ascending order and so reverses ties as well ([0, 2, 3, 1] for the same input). Errors: a non-vector matrix, desc that is not a boolean.

Overloads

One call shape — this function is not overloaded.

CodeInputOutputDescription
sortperm(x, [desc])
x vector or stringx is a numeric vector or a list of strings (byte order).
desc optionaldesc is true or false (default false).
not documented yetThe sort is stable in both directions: equal elements keep their original order, so sortperm([3, 1, 2, 1], true) is [0, 2, 1, 3]. NaN counts as the largest value (last ascending, first descending) and 0 equals -0.

Examples

From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.

xs = [3, 1, 2, 1, 3, 1]
print(sortperm(xs))
print(sortperm(xs, true))
print(argsort(xs, true))
print(xs[sortperm(xs)])
print(sortperm(("pear", "fig", "apple")))
output
[1, 3, 5, 2, 0, 4]
[0, 4, 2, 1, 3, 5]
[4, 0, 2, 5, 3, 1]
[1, 1, 1, 2, 3, 3]
[2, 1, 0]

from statistics-ml