everything
I found algorithms for generating permutations in lexicographical order from the Art of Computer Programming (TAOCP):
http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
Lexicographic generation There are many ways to systematically generate all permutations of a given sequence [edit]. One classic algorithm, which is simple and flexible, is based on finding the next permutation in lexicographical order, if it exists. It can handle repeated values, in which case it generates separate multi-multiply permutations every time. Even for ordinary permutations, it is much more efficient than generating values ββfor the Lehmer code in lexicographical order (possibly using a system of numerical numbers) and converting them to permutations. To use it, start by sorting the sequence in a (slightly) ascending order (which gives it a lexicographically minimal permutation), and then repeats the transition to the next permutation until it can be found. This method dates back to Narayana Pandita in India of the 14th century, and since then it has often been discovered.
The following algorithm generates the next permutation lexicographically after this permutation. It changes the given permutation in place.
- Find the largest index k such that a [k] a [k + 1]. If such an index does not exist, the permutation is the last permutation.
- Find the largest index l such that a [k] a [l]. Since k + 1 is such an index, l is well defined and satisfies k <l.
- Change a [k] to [l].
- Cancel the sequence from [k + 1] to the final element a and include it in [n].
After step 1, it is known that all elements strictly after position k form a weakly decreasing sequence; therefore, no permutation of these elements will force it to advance in lexicographic order; to advance you need to increase a [k]. Step 2 finds the smallest value a [l] to replace a [k], and replacing them in step 3 leaves the sequence after position k in a slightly decreasing order. Turning to this sequence in step 4, then its lexicographically minimal permutation is obtained, and the lexicographic successor of the initial state for the entire sequence
jeffjoy
source share