# 11 Algorithms library [algorithms]

## 11.5 Sorting and related operations [alg.sorting]

### 11.5.9 Permutation generators [alg.permutation.generators]

``` template <BidirectionalIterator I, Sentinel<I> S, class Comp = less<>, class Proj = identity> requires Sortable<I, Comp, Proj> bool next_permutation(I first, S last, Comp comp = Comp{}, Proj proj = Proj{}); template <BidirectionalRange Rng, class Comp = less<>, class Proj = identity> requires Sortable<iterator_t<Rng>, Comp, Proj> bool next_permutation(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}); ```

Effects: Takes a sequence defined by the range [first,last) and transforms it into the next permutation. The next permutation is found by assuming that the set of all permutations is lexicographically sorted with respect to comp and proj. If such a permutation exists, it returns true. Otherwise, it transforms the sequence into the smallest permutation, that is, the ascendingly sorted one, and returns false.

Complexity: At most (last - first)/2 swaps.

``` template <BidirectionalIterator I, Sentinel<I> S, class Comp = less<>, class Proj = identity> requires Sortable<I, Comp, Proj> bool prev_permutation(I first, S last, Comp comp = Comp{}, Proj proj = Proj{}); template <BidirectionalRange Rng, class Comp = less<>, class Proj = identity> requires Sortable<iterator_t<Rng>, Comp, Proj> bool prev_permutation(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}); ```

Effects: Takes a sequence defined by the range [first,last) and transforms it into the previous permutation. The previous permutation is found by assuming that the set of all permutations is lexicographically sorted with respect to comp and proj.

Returns: true if such a permutation exists. Otherwise, it transforms the sequence into the largest permutation, that is, the descendingly sorted one, and returns false.

Complexity: At most (last - first)/2 swaps.