# Previous and next permutation: prevperm nextperm

### 5.9.2 Previous and next permutation: prevperm nextperm

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 set of 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 one argument:
  p, a permutation.
- prevperm(p) returns the previous permutation in lexicographic order, or undef if there is no previous permutation.

#### Example.

Input:

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

Output:

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

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

#### Example.

Input:

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

Output:

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