Heap's algorithm
Heap's algorithm generates all possible permutations of objects. It was first proposed by B. R. Heap in 1963. The algorithm minimizes movement: it generates each permutation from the previous one by interchanging a single pair of elements; the other elements are not disturbed. In a 1977 review of permutation-generating algorithms, Robert Sedgewick concluded that it was at that time the most effective algorithm for generating permutations by computer.
The sequence of permutations of objects generated by Heap's algorithm is the beginning of the sequence of permutations of objects. So there is one infinite sequence of permutations generated by Heap's algorithm.
Details of the algorithm
For a collection containing different elements, Heap found a systematic method for choosing at each step a pair of elements to switch in order to produce every possible permutation of these elements exactly once.Described recursively as a decrease and conquer method, Heap's algorithm operates at each step on the initial elements of the collection. Initially and thereafter. Each step generates the permutations that end with the same final elements. It does this by calling itself once with the element unaltered and then times with the element exchanged for each of the initial elements. The recursive calls modify the initial elements and a rule is needed at each iteration to select which will be exchanged with the last. Heap's method says that this choice can be made by the parity of the number of elements operated on at this step. If is even, then the final element is iteratively exchanged with each element index. If is odd, the final element is always exchanged with the first.
// Output the k! permutations of A in which the first k elements are permuted in all ways.
// To get all permutations of A, use k := length of A.
//
// If k > length of A, will try to access A out of bounds.
// If k <= 0 there will be no output
procedure permutations:
if k = 1 then
output
else
// permutations with last element fixed
permutations
// permutations with last element swapped out
for i := 0; i < k-1; i += 1 do
if k is even then
swap
else
swap
end if
permutations
end for
end if
One can also write the algorithm in a non-recursive format.
procedure permutations:
// c is an encoding of the stack state.
// c encodes the for-loop counter for when permutations is called
c : array of int
for i := 0; i < n; i += 1 do
c := 0
end for
output
// i acts similarly to a stack pointer
i := 1;
while i < n do
if c < i then
if i is even then
swap
else
swap
end if
output
// Swap has occurred ending the while-loop. Simulate the increment of the while-loop counter
c += 1
// Simulate recursive call reaching the base case by bringing the pointer to the base case analog in the array
i := 1
else
// Calling permutations has ended as the while-loop terminated. Reset the state and simulate popping the stack by incrementing the pointer.
c := 0
i += 1
end if
end while
Proof
In this proof, we'll use the below implementation as Heap's algorithm as it makes the analysis easier, and certain patterns can be easily illustrated. While it is not optimal, the implementation is correct and will produce all permutations.// Output the k! permutations of A in which the first k elements are permuted in all ways.
// To get all permutations of A, use k := length of A.
//
// If, k > length of A, will try to access A out of bounds.
// If k <= 0 there will be no output
procedure permutations:
if k = 1 then
output
else
for i := 0; i < k; i += 1 do
permutations
if k is even then
swap
else
swap
end if
end for
end if
Claim: If array A has length, then
permutations will result in either A being unchanged, if is odd, or, if is even, then A is rotated to the right by 1.Base: If array has length 1, then
permutations will output A and stop, so A is unchanged. Since 1 is odd, this is what was claimed, so the claim is true for arrays of length 1.Induction: If the claim is true for arrays of length ≥ 1, then we show that the claim is true for arrays of length +1. Since the claim depends on whether is odd or even, we prove each case separately.
If is odd, then, by the induction hypothesis, for an array A of length,
permutations will not change A, and for the claim to hold for arrays of length +1, we need to show that permutations rotates A to the right by 1 position. Doing permutations will first do permutations and then in each iteration of the for-loop, swap the elements in positions and in A. The first swap puts element in position 0, and element 0 in position. The next swap puts the element in position in position 1 and element 1 in position. In the final iteration, the swap puts element -1 is in position, and the element in position in position -1. To illustrate the above, look below for the case = 4.
1,2,3,4... original array
1,2,3,4... 1st iteration
4,2,3,1... 1st iteration
4,2,3,1... 2nd iteration
4,1,3,2... 2nd iteration
4,1,3,2... 3rd iteration
4,1,2,3... 3rd iteration
4,1,2,3... 4th iteration
4,1,2,3... 4th iteration
The altered array is a rotated version of the original
If is even, then, by the induction hypothesis, for an array A of length,
permutations rotates A to the right by 1 position, and for the claim to hold for arrays of length +1, we need to show that permutations leaves A unchanged. Doing permutations will in each iteration of the for-loop, first do permutations and then, swap the elements in positions 0 and in A. Rotating the first elements and then swapping the first and last elements is equivalent to rotating the entire array. Since there are as many iterations of the loop as there are elements in the array, the entire array is rotated until each element returns to where it started. To illustrate the above, look below for the case = 5.
1,2,3,4,5... original array
4,1,2,3,5... 1st iteration
5,1,2,3,4... 1st iteration
3,5,1,2,4... 2nd iteration
4,5,1,2,3... 2nd iteration
2,4,5,1,3... 3rd iteration
3,4,5,1,2... 3rd iteration
1,3,4,5,2... 4th iteration
2,3,4,5,1... 4th iteration
5,2,3,4,1... 5th iteration
1,2,3,4,5... 5th iteration
The final state of the array is in the same order as the original
The induction proof for the claim is now complete, which will now lead to why Heap's Algorithm creates all permutations of array. Once again we will prove by induction the correctness of Heap's Algorithm.
Basis: Heap's Algorithm trivially permutes an array of size as outputting is the one and only permutation of.
Induction: Assume Heap's Algorithm permutes an array of size. Using the results from the previous proof, every element of will be in the "buffer" once when the first elements are permuted. Because permutations of an array can be made by altering some array through the removal of an element from then tacking on to each permutation of the altered array, it follows that Heap's Algorithm permutes an array of size, for the "buffer" in essence holds the removed element, being tacked onto the permutations of the subarray of size. Because each iteration of Heap's Algorithm has a different element of occupying the buffer when the subarray is permuted, every permutation is generated as each element of has a chance to be tacked onto the permutations of the array without the buffer element.
Frequent mis-implementations
It is tempting to simplify the recursive version given above by reducing the instances of recursive calls. For example, as:procedure permutations:
if k = 1 then
output
else
// Recursively call once for each k
for i := 0; i < k; i += 1 do
permutations
// swap choice dependent on parity of k
if k is even then
// no-op when i k-1
swap
else
// XXX incorrect additional swap when ik-1
swap
end if
end for
end if
This implementation will succeed in producing all permutations but does not minimize movement. As the recursive call-stacks unwind, it results in additional swaps at each level. Half of these will be no-ops of and where but when is odd, it results in additional swaps of the with the element.
| swaps | additional = swaps | ||
| 1 | 0 | 0 | 0 |
| 2 | 1 | 1 | 0 |
| 3 | 5 | 6 | 1 |
| 4 | 23 | 27 | 4 |
| 5 | 119 | 140 | 21 |
| 6 | 719 | 845 | 126 |
| 7 | 5039 | 5922 | 883 |
| 8 | 40319 | 47383 | 7064 |
| 9 | 362879 | 426456 | 63577 |
These additional swaps significantly alter the order of the prefix elements.
The additional swaps can be avoided by either adding an additional recursive call before the loop and looping times or looping times and checking that is less than as in:
procedure permutations:
if k = 1 then
output
else
// Recursively call once for each k
for i := 0; i < k; i += 1 do
permutations
// avoid swap when ik-1
if
// swap choice dependent on parity of k
if k is even then
swap
else
swap
end if
end if
end for
end if
The choice is primarily aesthetic but the latter results in checking the value of twice as often.