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  elements. Each permutation in the sequence that it generates differs from the previous permutation by swapping two adjacent elements of the sequence. Equivalently, this algorithm finds a Hamiltonian cycle in the permutohedron.

This method was known already to 17th-century English change ringers, and  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 permutations that it generates may be sped up because of the similarity between consecutive permutations that it generates.

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  can be formed from the sequence of permutations for  by placing the number  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  blocks of permutations, so that within each block the permutations agree on the ordering of the numbers from 1 to  and differ only in the position of . The blocks themselves are ordered recursively, according to the Steinhaus–Johnson–Trotter algorithm for one less element.
Within each block, the positions in which  is placed occur either in descending or ascending order, and the blocks alternate between these two orders: the placements of  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:

The same placement pattern, alternating between descending and ascending placements of , applies for any larger value of .
In sequences of permutations with this recursive structure, each permutation differs from the previous one either by the single-position-at-a-time motion of , or by a change of two smaller numbers inherited from the previous sequence of shorter permutations. In either case this difference is just the transposition of two adjacent elements. When  the first and final elements of the sequence, also, differ in only two adjacent elements (the positions of the numbers  and ), as may be proven by induction.

This sequence may be generated by a recursive algorithm that constructs the sequence of smaller permutations and then performs all possible insertions of the largest number into the recursively-generated sequence. The same ordering of permutations can also be described equivalently as the ordering generated by the following greedy algorithm.
Start with the identity permutation .
Now repeatedly transpose the largest possible entry with the entry to its left or right, such that in each step, a new permutation is created that has not been encountered in the list of permutations before. For example, in the case  the sequence starts with , then flips  with its left neighbor to get .
From this point, flipping  with its right neighbor  would yield the initial permutation , so the sequence instead flips  with its left neighbor  and arrives at , etc. The direction of the transposition (left or right) is always uniquely determined in this algorithm.
However, the actual Steinhaus–Johnson–Trotter algorithm does not use recursion, and does not need to keep track of the permutations that it has already encountered. Instead, it computes the same sequence of permutations by a simple iterative method.

Original version
As described by , the algorithm for generating the next permutation from a given permutation  performs the following steps.
For each  from 1 to , let  be the position where the value  is placed in permutation . If the order of the numbers from 1 to  in permutation  defines an even permutation, let  otherwise, let .
Find the largest number  for which  defines a valid position in permutation  that contains a number smaller than . Swap the values in positions  and .
When no number  can be found meeting the conditions of the second step of the algorithm, the algorithm has reached the final permutation of the sequence and terminates.
This procedure may be implemented in  time per permutation.

 gives an alternative implementation of an iterative algorithm for the same sequence, in lightly commented ALGOL 60 notation.

Because this method generates permutations that alternate between being even and odd, it may easily be modified to generate only the even permutations or only the odd permutations: to generate the next permutation of the same parity from a given permutation, simply apply the same procedure twice.

Even's speedup
A subsequent improvement by Shimon Even provides an improvement to the running time of the algorithm by storing additional information for each element in the permutation: its position, and a direction (positive, negative, or zero) in which it is currently moving (essentially, this is the same information computed using the parity of the permutation in Johnson's version of the algorithm). Initially, the direction of the number 1 is zero, and all other elements have a negative direction:

At each step, the algorithm finds the greatest element with a nonzero direction, and swaps it in the indicated direction:

If this causes the chosen element to reach the first or last position within the permutation, or if the next element in the same direction is greater than the chosen element, the direction of the chosen element is set to zero:

After each step, all elements greater than the chosen element (which previously had direction zero) have their directions set to indicate motion toward the chosen element.  That is, positive for all elements between the start of the permutation and the chosen element, and negative for elements toward the end. Thus, in this example, after the number 2 moves, the number 3 becomes marked with a direction again:

The remaining two steps of the algorithm for  are:

When all numbers become unmarked, the algorithm terminates.

This algorithm takes time  for every step in which the greatest number to move is . Thus, the swaps involving the number  take only constant time; since these swaps account for all but a  fraction of all of the swaps performed by the algorithm, the average time per permutation generated is also constant, even though a small number of permutations will take a larger amount of time.

A more complex loopless version of the same procedure allows it to be performed in constant time per permutation in every case; however, the modifications needed to eliminate loops from the procedure make it slower in practice.

Related structures

Permutohedron
The set of all permutations of  items may be represented geometrically by a permutohedron, the polytope formed from the convex hull of  vectors, the permutations of the vector . Although defined in this way in -dimensional space, it is actually an -dimensional polytope; for example, the permutohedron on four items is a three-dimensional polyhedron, the truncated octahedron. If each vertex of the permutohedron is labeled by the inverse permutation to the permutation defined by its vertex coordinates, the resulting labeling describes a Cayley graph of the symmetric group of permutations on  items, as generated by the permutations that swap adjacent pairs of items. Thus, each two consecutive permutations in the sequence generated by the Steinhaus–Johnson–Trotter algorithm correspond in this way to two vertices that form the endpoints of an edge in the permutohedron, and the whole sequence of permutations describes a Hamiltonian path in the permutohedron, a path that passes through each vertex exactly once. If the sequence of permutations is completed by adding one more edge from the last permutation to the first one in the sequence, the result is instead a Hamiltonian cycle.

Gray codes
A Gray code for numbers in a given radix is a sequence that contains each number up to a given limit exactly once, in such a way that each pair of consecutive numbers differs by one in a single digit. The  permutations of the  numbers from 1 to  may be placed in one-to-one correspondence with the  numbers from 0 to  by pairing each permutation with the sequence of numbers  that count the number of positions in the permutation that are to the right of value  and that contain a value less than  (that is, the number of inversions for which  is the larger of the two inverted values), and then interpreting these sequences as numbers in the factorial number system, that is, the mixed radix system with radix sequence  For instance, the permutation  would give the values , , , , and . The sequence of these values, , gives the number

Consecutive permutations in the sequence generated by the Steinhaus–Johnson–Trotter algorithm have numbers of inversions that differ by one, forming a Gray code for the factorial number system.

More generally, combinatorial algorithms researchers have defined a Gray code for a set of combinatorial objects to be an ordering for the objects in which each two consecutive objects differ in the minimal possible way. In this generalized sense, the Steinhaus–Johnson–Trotter algorithm generates a Gray code for the permutations themselves.

History
The method was known for much of history as a method for change ringing of church bells: it gives a procedure by which a set of bells can be rung through all possible permutations, changing the order of only two bells per change. These so-called "plain changes" were recorded as early as 1621 for four bells, and a 1677 book by Fabian Stedman lists the solutions for up to six bells. More recently, change ringers have abided by a rule that no bell may stay in the same position for three consecutive permutations; this rule is violated by the plain changes, so other strategies that swap multiple bells per change have been devised.

The algorithm is named after Hugo Steinhaus, Selmer M. Johnson and Hale F. Trotter. Johnson and Trotter rediscovered the algorithm independently of each other in the early 1960s. A book by Steinhaus, originally published in 1958 and translated into English in 1963, describes a related puzzle of generating all permutations by a system of particles, each moving at constant speed along a line and swapping positions when one particle overtakes another. No solution is possible for , because the number of swaps is far fewer than the number of permutations, but the Steinhaus–Johnson–Trotter algorithm describes the motion of particles with non-constant speeds that generate all permutations.

See also
 Heap's algorithm, a different method for listing all permutations
 Fisher–Yates shuffle, a method for generating random permutations

Notes

References

. Although Dijkstra does not cite any prior literature, an earlier draft EWD502 reveals that he knew of .

; see Section 2.1, "A minimum-change generator", pp. 3–8

Combinatorial algorithms
Permutations