[This page is auto-generated; please prefer to read the article’s PDF Form.]
Suppose, in our program we are generating permutations in array a itself, and at certain point have generated some permutation P in it:
|
What is the permutation P′ which is the very next permutation of P in the lexicographic ordering? That is, among all permutations larger than P, P′ is the smallest.
Say, the first element at which P and P′ differ is their mth element. Call the mth element in P′ as b. So, am−1≠b and since P < P′, am−1 < 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 am−1) implies Q < P′. So, P < Q < P′. That is a contradiction, since P′ is 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:
| (1) |
Since P′ shares its first m− 1 elements with P, and its mth element b differs from am−1, we can say that b is one of the remaining N − m elements of P, referred as set S:
|
Note that elements of S can be ordered as in (1). Since P′ is the smallest of all permutations larger than P, b has to be the smallest of the elements in set S such that b > am−1. Say, b = ak. Since am is the largest in set S, such b exists only if:
| (2) |
The elements in P′ after its mth element b are actually this set of N − m elements: S′ = (S ∖{ak}) ∪{am−1}.
Again, since P′ is the smallest of all permutations larger than P, all N − m elements in P′ after b must be in increasing order. That is, elements of set S′ in 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 am−1. Since ak is the smallest element in set S which is larger than am−1, so, in that ordering, ak can be removed and am−1 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.
Copyright © 2021 Nitin Verma. All rights reserved.