Title: Generating Permutations
1Generating Permutations
- Bottom Up
- Johnson-Trotter
- Lexicographic
2Bottom Up Permutations
- Given the (n1)! permutations of 1,,n1,
insert n into each position of each of them. - This generates n! permutations of 1,,n.
- Base step 1
- Step 1 1 2, 2 1
- Step 2 1 2 3, 1 3 2, 3 1 2 3 2 1, 2 3 1, 2
1 3 - Step 3 1234, 1243, 1423, 4123 4132, 1432,
1342, 1324 - 3124, 3142, 3412, 4312 4321, 3421,
3241, 3214 - 2314, 2341, 2431, 4231 4213, 2413,
2143, 2134 - Notice the ordering This is called minimal
change.
3Mobile Elements forMinimal Change Algorithm
- If each element has an associated direction, then
we call those elements mobile that are facing
smaller adjacent elements. - ????
- 3 2 4 1
- In this example, 3 4 are mobile, while 1 2
are not. - We start out with the increasing permutation,
with each element facing left.
4Johnson-Trotter Algorithm
- INPUT a positive integer n
- OUTPUT list of all permutations of 1,,n
- initialize first permutation
- while ? a mobile element do
- find the largest mobile element k
- swap k and the adjacent element it is facing
- reverse the direction of all elements larger than
k - print current permutation
5Example
1 2 3 4
6Example
1 2 3 4 1 2 4 3
7Example
1 2 3 4 1 2 4 3 1 4 2 3
8Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3
9Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3 4 1 3 2
10Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3 4 1 3 2 1 4 3 2
11Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3 4 1 3 2 1 4 3 2 1
3 4 2
12Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3 4 1 3 2 1 4 3 2 1
3 4 2 1 3 2 4
13Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3 4 1 3 2 1 4 3 2 1
3 4 2 1 3 2 4 3 1 2 4
14Example
1 2 3 4 1 2 4 3 1 4 2 3 4 1 2 3 4 1 3 2 1 4 3 2 1
3 4 2 1 3 2 4 3 1 2 4 3 1 4 2
15Example
1 2 3 4 1 2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