### 12.2.2 Previous and next permutation

The set of n-tuples of an ordered set can be put in lexicographic order, where the tuple (a1,a2,…,an) comes before (b1,b2,…,bn) exactly when for some k (possibly k=0), ai=bi for i=1,…,k−1 and ak<bk. For example, the list of all permutations of size 3 in lexicographic order is: (0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0).

The prevperm and nextperm commands find the preceding and succeeding permutation.

- prevperm takes p, a permutation.
- prevperm(p) returns the previous permutation in lexicographic order, or undef if there is no previous permutation.
- nextperm takes p, a permutation.
- nextperm(p) returns the next permutation in lexicographic order, or undef if there is no next permutation.

#### Examples

prevperm([0,3,1,2])

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

nextperm([0,2,3,1])

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