Sorting by a permutation

### 6.3.20 Sorting by a permutation

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.
- sortperm is useful when several lists of equal lengths need to be sorted in the same order. Sorting by permutation is optimally efficient.

#### Examples

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

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

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

| ⎡ ⎣ | “bc”,“de”,“cd”,“ab”,“ad” | ⎤ ⎦