#Generating permutations, an algorithmic perspective
##Abstract
The focus of this paper is the implementation of two permutation generation algorithms, namely Lexicographic Order Generation and Steinhaus–Johnson–Trotter.
The Lexicographic Order Generation algorithm is the fastest algorithm to find the next lexicographic permutation.
It is currently the de facto implementation in many languages. std::next_permutation is implemented using this algorithm.
- Find largest index
isuch thatarray[i − 1] < array[i]. (If no such i exists, then this is already the last permutation.) - Find largest index
jsuch thatj ≥ iandarray[j] > array[i − 1]. - Swap
array[j]andarray[i − 1]. - Reverse the suffix starting at
array[i].
At most
The Steinhaus–Johnson–Trotter is a formalisation of a very old permutation generation algorithm. It works by swapping adjacent elements from the previous permutation. The following implementation uses Shimon Even's modification, adding a direction to each elements.
- Sort the set in lexicographical order and associate
LEFTas the direction for each of the elements - Find the largest mobile integer and swap it with the adjacent element on its direction without changing the direction of any of these two.
- Check if there’s any number, larger than the current largest mobile integer. If there’s one or more, change the direction of all of them.
At most
##Results
| Number of elements | LOG | SJT | STL |
|---|---|---|---|
| 11! | 0m0.172s | 0m2.340s | 0m0.161s |
| 12! | 0m1.856s | 0m31.980s | 0m1.760s |
| 13! | 0m23.941s | --------- | 0m21.679s |