Sorting by permutation: sortperm

### 5.40.21 Sorting by permutation: sortperm

The sortperm command returns the permutation which sorts the given list in ascending order or the list sorted by the given permutation.

sortperm takes one or two arguments:

- V, a nonempty list.
- P, a permutation (optional).

If called with one argument, sortperm returns the permutation which sorts the list V in ascending order. If called with two arguments, it returns a copy of V sorted according to P.

This command is useful when several lists of equal lengths need to be sorted in the same order. Sorting by permutation is optimally efficient.

#### Examples.

- Input:
  V:=[30,25,40,10,20]; P:=sortperm(V)
- Output:

  ⎡ ⎣ | 3,4,1,0,2 | ⎤ ⎦

- Input:
  S:=["ab","cd","ad","bc","de"]; sortperm(S,P)
- Output:

  ⎡ ⎣ | "bc","de","cd","ab","ad" | ⎤ ⎦