Home

[This page is auto-generated; please prefer to read the article’s PDF Form.]



[Prev]   [Up]   [Next]   

Next in Lexicographical Order

Suppose, in our program we are generating permutations in array a itself, and at certain point have generated some permutation P in it:

P = (a0,a1,a2,...,aN− 1)

What is the permutation Pwhich is the very next permutation of P in the lexicographic ordering? That is, among all permutations larger than P, Pis the smallest.

Say, the first element at which P and Pdiffer is their mth element. Call the mth element in Pas b. So, am1b and since P < P, am1 < b.

Note that, among all permutations having their first m elements’ sequence same as P, P must be the largest. Because, if P is not the largest, then there is a permutation Q larger than P sharing first m elements’ sequence with it. That is, P < Q. The initial m elements of Q being same as of P (till am1) implies Q < P. So, P < Q < P. That is a contradiction, since Pis the very next permutation after P.

Since P is the largest among all permutations having their first m elements’ sequence same as P, we can conclude this about the remaining N m elements of P:

am > am+1  > am+2 > ...>  aN−1
(1)

Since Pshares its first m1 elements with P, and its mth element b differs from am1, we can say that b is one of the remaining N m elements of P, referred as set S:

S = {am, am+1,am+2, ...,aN− 1}

Note that elements of S can be ordered as in (1). Since Pis the smallest of all permutations larger than P, b has to be the smallest of the elements in set S such that b > am1. Say, b = ak. Since am is the largest in set S, such b exists only if:

am −1 < am
(2)

The elements in Pafter its mth element b are actually this set of N m elements: S= (S ∖{ak}) ∪{am1}.

Again, since Pis the smallest of all permutations larger than P, all N m elements in Pafter b must be in increasing order. That is, elements of set Sin increasing order.

We already know the order of elements of set S from ordering (1). That ordering can be modified by removing ak and adding am1. Since ak is the smallest element in set S which is larger than am1, so, in that ordering, ak can be removed and am1 added at the same position, while maintaining the decreasing order. This modification in (1) gives us a decreasing order of elements of set S, which can be reversed to obtain increasing order.

[Prev]   [Up]   [Next]