The Steinhaus–Johnson–Trotter algorithm or Johnson–Trotter algorithm, also called plain changes, is an algorithm named after Hugo Steinhaus, Selmer M. Johnson and Hale F. Trotter that generates all of the permutations of n {\displaystyle n} elements. Each two adjacent permutations in the resulting sequence differ by swapping two adjacent permuted elements. Equivalently, this algorithm finds a Hamiltonian cycle in the permutohedron, a polytope whose vertices represent permutations and whose edges represent swaps. This method was known already to 17th-century English change ringers, and Robert Sedgewick calls it "perhaps the most prominent permutation enumeration algorithm". A version of the algorithm can be implemented in such a way that the average time per permutation is constant. As well as being simple and computationally efficient, this algorithm has the advantage that subsequent computations on the generated permutations may be sped up by taking advantage of the similarity between consecutive permutations.
Algorithm The sequence of permutations generated by the Steinhaus–Johnson–Trotter algorithm has a natural recursive structure, that can be generated by a recursive algorithm. However the actual Steinhaus–Johnson–Trotter algorithm does not use recursion, instead computing the same sequence of permutations by a simple iterative method. A later improvement allows it to run in constant average time per permutation.
Recursive structure The sequence of permutations for a given number n {\displaystyle n} can be formed from the sequence of permutations for n − 1 {\displaystyle n-1} by placing the number n {\displaystyle n} into each possible position in each of the shorter permutations. The Steinhaus–Johnson–Trotter algorithm follows this structure: the sequence of permutations it generates consists of ( n − 1 ) ! {\displaystyle (n-1)!} blocks of permutations, so that within each block the permutations agree on the ordering of the numbers from 1 to n − 1 {\displaystyle n-1} and differ only in the position of n {\displaystyle n} . The blocks themselves are ordered recursively, according to the Steinhaus–Johnson–Trotter algorithm for one less element. Within each block, the positions in which n {\displaystyle n} is placed occur either in descending or ascending order, and the blocks alternate between these two orders: the placements of n {\displaystyle n} in the first block are in descending order, in the second block they are in ascending order, in the third block they are in descending order, and so on. Thus, from the single permutation on one element,
one may place the number 2 in each possible position in descending order to form a list of two permutations on two elements,
Then, one may place the number 3 in each of three different positions for these two permutations, in descending order for the first permutation 1 2, and then in ascending order for the permutation 2 1:
… excerpt ends here. Continue reading the full article.



