Volume C1 · Basic concepts · TAOCP Section 1.3.3
Applications to permutations
Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.
Read it next to Section 1.3.3 of the book. The nodes and the exercises of the section.
Applications to permutations, cycle products and inverses in place
Overview
Section 1.3.3 of TAOCP has two aims. It gives four programs for MIX that are longer than those of Section 1.3.2, and it uses them to teach the structure of a permutation. A permutation can be seen as a rearrangement of objects, and then it falls apart into disjoint cycles. The section writes down this notation, defines the product of two permutations, and builds two algorithms that multiply a list of cycles. Algorithm A works like a person: it scans the input again and again, once for each step of each output cycle. Algorithm B works like a machine: it scans the input once from right to left and keeps the whole current permutation in a table. Then the section shows two ways to replace a permutation of by its inverse inside the same array, Algorithm I (by cycles, with signs as marks) and Algorithm J (by a chain of positive links). The programs are analysed along the way. The last part of the section turns to random permutations. It counts the cycles of a random permutation with the Stirling numbers of the first kind, and it counts the fixed points with derangement numbers and with the principle of inclusion and exclusion.
The section uses Section 1.2.5 for permutations, Section 1.2.6 for binomial coefficients and for the Stirling numbers, Section 1.2.7 for the harmonic numbers, Section 1.2.10 for the mean and the deviation of a count with a generating function, and Section 1.3.2 for MIX programs with frequency counts. C1 proves every statement of the section on its own, with examples that C1 made and ran, and it fixes the meaning of each count by running the MIX programs of this chapter on a MIX simulator. The listings themselves are not printed here. The reader has them in the book, and the chapter describes the structure of each program and the work of each group of lines.
The ideas
A permutation has two pictures, a table and a set of cycles. The table (two-line form) lists each object and its image. The cycle form follows an object to its image, to the image of the image, and so on until the chain returns. Each object lies on exactly one such closed chain. So a permutation is the same thing as a set of disjoint cycles. The cycle form is shorter, and it shows the structure: the lengths of the cycles, the fixed points, the order of the permutation.
The product of permutations means one after the other, read from left to right. The text writes for the permutation that applies first. The product of a list of cycles is therefore found by following an object through the cycles from the left. The list does not have to be disjoint. The answer is a permutation, and the work of Algorithms A and B is to write the answer as disjoint cycles.
Algorithm A tags symbols. Algorithm B keeps a table. In Algorithm A, each symbol of the input formula that has been used is marked, and the algorithm builds each output cycle by repeated scans of the formula. In Algorithm B, the algorithm reads the formula from the right and keeps, for each name, its image under the part of the formula that it has read. The table needs one exchange for each symbol, plus a search for the name in a list when the names are not numbers. Algorithm A makes a pass over the whole formula for each name, while Algorithm B reads the formula once. This is why the two programs differ in time by a large factor.
A MIX analysis is a puzzle about counts. For each group of lines, name the number of executions. Kirchhoff's first law (flow in equals flow out) links the numbers. The remaining numbers have a meaning in the data, such as the number of cycles in the input. A few counts link in a way that only the structure of the problem shows, and one of them (the sum of the three scan steps) needs a special argument.
Inverting in place is a rewiring of cycles. To invert a permutation, point each arrow backwards. When the array may not grow, each cycle is rewired one entry at a time, and the algorithm needs a mark for the entries that it has already treated. Algorithm I marks with a minus sign. Algorithm J puts a minus sign on every entry first, and then it uses chains of positive entries as a stack of links. Algorithm I does a fixed amount of work per entry, and Algorithm J does work that grows like on average.
Random permutations: cycles are left-to-right minima, and fixed points have the same statistics for all . If the cycles are written in a fixed canonical order, the parentheses can be dropped without loss, and the cycles become the left-to-right minima of a linear arrangement. This turns the number of cycles into a quantity that Section 1.2.10 has already studied. The number of fixed points is a different problem. The answer is the sum of terms , whose derivative is the same sum with one term less. This gives the mean and the variance , for every .
C1 differs from the book in these points. It does not use the examples of the book: every example is new and was checked by a program. It proves the correctness of Algorithms A, B and J with explicit invariants, where the book leaves the proofs to the reader or to exercises. It derives the running time of Program B in full (the book leaves this to exercise 10), and it finds the average of the count of Algorithm J (the book leaves this to exercise 14), which shows the time of Algorithm J.
Definitions, results and proofs
Definition (permutation, two-line form, cycle form, TAOCP Section 1.3.3). A permutation of a finite set is a bijection of to itself. The two-line form of a permutation writes the elements of in any order in the top row and, under each element , the image . A cycle with distinct elements is the permutation that maps and fixes all other elements. The cycle form of is a list of cycles with pairwise disjoint sets of elements whose product is . The list leaves out the cycles with one element (the fixed points), and the empty list is written and stands for the identity.
Node: 1.3.3-def-permutation · Lean: not yet stated
Explanation. A permutation can be read in two ways. As a rearrangement, the object moves to the place where stood. As a renaming, the object named gets the new name . The two-line form does not depend on the order of the columns, so a permutation of objects has two-line forms. A cycle of one element is the identity on every element, which is why the cycle form can leave it out. The identity has no cycle of length or more, and the symbol marks this. The next result says that the cycle form always exists and that it is almost unique.
Example. Let be the map on . The images of are . They are distinct, so is a permutation. Follow : , a cycle . Follow : , a cycle . The elements , and are fixed ( and ). So the cycle form is . The two cycles of length and the three fixed points use elements, so no element is lost.
Proof of the existence and the uniqueness of the cycle form. Let be a permutation of a finite set and let . Put . Since is finite, some value repeats. Let be the first value that equals an earlier one, say with . If , then , because are distinct and and . But , which contradicts the injectivity of . So , and is a cycle that agrees with on its elements. Call its element set the orbit of . Two orbits are equal or disjoint: if they share an element, then the chain from that element is in both, and each chain contains the other starting point. Hence splits into disjoint orbits, and the product of the cycles of the orbits equals on each element. Dropping the orbits of size gives the cycle form. For uniqueness, take any cycle form. Each cycle lists an orbit of , because the chain stays in the cycle that contains . So each cycle of a cycle form is a rotation of the orbit cycle, and the orbit cycles are unique up to the order in which the cycles are written. The cycle form is thus unique up to the order of the cycles and the choice of the first element in each cycle.
Example (a permutation of six letters in two-line form, TAOCP eq. 1.3.3(1)). The permutation of that sends , , , , , has the two-line form
Node: 1.3.3-(1) · Lean: not yet stated
Explanation. Each column has an object above and its image below. Under the rearrangement reading, the object at place moves to place (first column). Under the renaming reading, the name becomes the name . The bottom row is a rearrangement of the top row, which is what makes a permutation: no two columns have the same image.
Example. The same permutation can be written with the columns in the reverse order:
Each column is a column of the first table, so this is the same permutation. Altogether there are two-line forms of , one for each order of the six columns.
Proof. The bottom row of the table above lists . These are the six letters, each once, so is a bijection, hence a permutation. A two-line form is a choice of an order for the columns. Two different orders give different strings, and each order gives a valid form, so the number of forms is .
Example (the same permutation in cycle form, TAOCP eq. 1.3.3(2)). The permutation of eq. 1.3.3(1) is
Node: 1.3.3-(2) · Lean: not yet stated
Explanation. Start at : . This closes the cycle . The letter is not yet used: closes . All six letters are used, so the list is complete. The cycle form shows that has two cycles of length and no fixed point.
Example. A fixed point does not appear in the cycle form. Take the permutation with , , , , , . Its cycle form is . The letter is a fixed point and does not appear.
Proof. Apply the existence argument of the definition to with and then . It gives the two orbits and , and the cycles above.
Example (other cycle forms of the same permutation, TAOCP eq. 1.3.3(3)). The permutation of eq. 1.3.3(2) can also be written , and . The string is a different permutation. In all, has cycle forms without fixed points.
Node: 1.3.3-(3) · Lean: not yet stated
Explanation. A cycle may start at any of its elements, and the cycles may come in any order, because disjoint cycles do not interact. A cycle may not be reversed: sends to , while sends to . The reverse of a cycle is its inverse.
Example. The string sends , but , so the string is not . The count is : two orders of the two cycles, three starting points for each cycle. A permutation with one cycle of length and one of length has cycle forms.
Proof of the count. Suppose that the cycle form of has cycles of lengths (all at least ). A way to write is an order of the cycles and, for each cycle, a choice of a starting element. By the uniqueness part of the definition, each such choice gives a valid form, and different choices give different strings (the strings differ in the order of their first symbols or in a first symbol of a cycle, since the elements are distinct). The number of choices is . For , and , so the count is .
Definition (the product of two permutations, TAOCP eq. 1.3.3(4)). Let and be permutations of the same set . The product is the permutation that applies first and second:
Node: 1.3.3-(4) · Lean: not yet stated
Explanation. The product of permutations is the composition of the maps, written in the order in which the maps act. Two facts follow at once. The product is associative, so a product of many factors needs no parentheses. The product is not commutative. A reader who knows composition of functions will see that here is the function . Many books on algebra use the other order, and so does Mathlib, where Equiv.Perm.mul_apply states . When C1 quotes a Lean result about products, C1 states the order.
Example. Let be as above and let , that is with fixed. For (first , then ): , , , , , . In two-line form
For (first , then ): , , , , , :
The two products differ ( goes to in one and to in the other).
Proof. The product is a bijection of , because a composition of bijections is a bijection. The product is associative: for three permutations, . The identity map is a unit on both sides. The example shows two permutations with , so the product is not commutative in general.
Example (a product of permutations in cycle form, TAOCP eq. 1.3.3(5)). With , the product of and the permutation is
Node: 1.3.3-(5) · Lean: not yet stated
Explanation. A cycle form is itself a product of permutations: the disjoint cycles and commute, and their product is . So a product of cycle forms is a longer list of cycles, and the notation does not need a multiplication sign. The list is not disjoint, because occurs in and in . The answer is found by following each letter through the four factors from left to right.
Example. The trace of each letter, with one column for each factor, is
| Letter | after | after | after | after |
|---|---|---|---|---|
The last column is the product: , , , , , . The cycles are and .
Proof. A product of factors maps to by the definition of eq. 1.3.3(4) and induction on . Each column of the table applies one factor to the entries of the column before. A cycle maps for and , and it fixes every letter outside. Row : fixes , maps , maps , fixes . The other rows follow in the same way. The cycle form of the final column is then read by the proof of the definition: and .
Example (the product that the programs compute, TAOCP eq. 1.3.3(6)). The input of Algorithms A and B is a formula, a list of cycles in which one letter may occur many times. For example, the formula
has the value . The programs of this section take such a formula and produce the disjoint cycle form of its value.
Node: 1.3.3-(6) · Lean: not yet stated
Explanation. The hand method follows one letter at a time through the factors and writes the answer cycle by cycle: find the image of the first unused letter, then the image of that image, and so on until the chain returns to the first letter. The method needs only the rule of the product, but it scans the whole formula once for each step of each output cycle. This is the method that Algorithm A turns into a program.
Example. The trail of each letter through the four factors is:
| Letter | start | after | after | after | after |
|---|---|---|---|---|---|
So , which is the cycle , and , which is .
Proof. The table is computed with the rule of the product, as in the example above. Check one row: goes to in ; goes to in ; is not in ; goes to in . A permutation of six letters in which and has the cycle form by the definition of the cycle form.
Algorithms and programs
Algorithm (multiplication of permutations in cycle form by repeated scans, TAOCP Algorithm 1.3.3A). Input: a formula, that is a list of cycles over names, where a name may occur in several cycles and in one cycle at most once. Output: the cycle form of the product of the formula, with fixed points left out. The algorithm tags the symbols that it has used, and it writes the output cycles one at a time. For each output element it makes one pass from left to right over the whole formula.
Node: Algorithm 1.3.3A · Lean: not yet stated
The idea. To find the image of a name under the formula, carry a value , start with , and read the cycles from left to right. In each cycle that contains , replace by the symbol that follows in the cycle (the first symbol of the cycle if is the last). At the end is the image of . The algorithm does this for the elements of an output cycle one after the other. It marks each symbol that it uses. A symbol that no pass has used yet is the start of an output cycle that has not been written. This works because each name is the start of a path through the formula, and the paths of different names do not share a symbol (the proof below).
The steps. In the steps, a closing copy is the symbol that replaces the closing parenthesis of a cycle. It has the name of the first symbol of the cycle.
A1. For each cycle, replace ")" by a closing copy of its first symbol.
Mark every proper symbol (not "(", not a closing copy) as untagged.
Set the output to empty.
A2. Find the leftmost untagged proper symbol. If none exists, go to A6.
Else put START <- that name, append "(" and START to the output,
tag that symbol, and set v <- the symbol that follows it.
Set the pass position p to the cell after the one that holds v.
A3. Pass over the cells from p to the right end.
For each cell c whose name equals v: tag c, set v <- the symbol in the cell
that follows c, and continue after that cell.
A4. If v differs from START, append v to the output, set p <- first cell,
and go to A3.
A5. Append ")" to the output. If the cycle just written has the form "(START)",
delete it. Go to A2.
A6. Stop. The output is the answer. If it is empty, the answer is ().
A worked run. Let the formula be . After A1 the cells are (with for a closing copy) ( a b c a* ( a b a* ( d e d*. Thirteen cells are in use. By the numbering of eq. 1.3.3(19), , , , . The run is:
| Step | START | Cells tagged in this step | at the end of the pass | Output after the step |
|---|---|---|---|---|
| A2, A3 | cell of in cycle 1, then in cycle 2 | (a |
||
| A5 | START, so close; the cycle is and is deleted | empty | ||
| A2, A3 | in cycle 1 | (b |
||
| A4, A3 | in cycle 1, then in cycle 2 | (b c |
||
| A5 | close | (b c) |
||
| A2, A3 | in cycle 3 | (b c)(d |
||
| A4, A3 | in cycle 3 | (b c)(d e |
||
| A5 | close | (b c)(d e) |
Then A2 finds no untagged proper cell (the proper cells are and all seven are tagged), and the answer is . Direct check with the rule of the product: in cycle 1, , then in cycle 2, , and cycle 3 fixes , so . For : cycle 1 gives , and the later cycles fix , so . For : cycle 1 gives , cycle 2 gives , cycle 3 fixes , so . Only cycle 3 moves and , so they exchange. The answer matches. The algorithm made five passes, one for each of the five names.
Correctness. For a name , the path of is the sequence of cells that the value uses when starts as and the pass goes through the formula from the left. The pass tags each cell that matches and moves past it. Four facts prove the algorithm.
- A closing copy never matches in a pass. Let a cycle be and let be its closing copy with the name . A pass that has meets the cell of before , matches it, and gets (or again only if , and then the match skips because it is the cell that follows). The names in a cycle are distinct, so no later cell of the cycle matches. If on arrival, the closing copy does not match. In all cases the closing copy is only read as the symbol that follows .
- The pass of gives the image of at the end. This follows from the rule of the product and from fact 1, by induction on the number of cycles read.
- Every proper cell lies on the path of exactly one name. The cell in cycle with name is matched when at cycle , and at cycle is for the name whose path is followed (here is the product of the cycles before ). So lies on the path of and on no other.
- A pass of the name starts at the first cell of the formula that has the name . No cycle before contains , so when the pass arrives at , and lies on the path of by fact 3. The cells on the path of are tagged only by the pass of .
The algorithm keeps this invariant: when A2 runs, the names of the closed output cycles form a union of orbits, and the pass of every such name has run, so all cells on their paths are tagged. Hence a name that is not in a closed cycle has the cell untagged, and A2 does not stop while such a name exists. Let be the leftmost untagged proper cell and let be its name. The cell is untagged, and it is not to the right of , so . The pass of then starts exactly at , and the cells to the left of do not change in this pass. So the first pass of the output cycle can start after with set to the symbol that follows .
The passes of A3 and A4 follow by fact 2 until returns to START. This closes an orbit of , and the passes tag the paths of all its names. The orbits that the algorithm writes are disjoint, so each name is written once. A name of the formula that is not written has an untagged first cell, so A2 would not have stopped. A name with an orbit of length 1 gives the cycle , which A5 deletes.
Termination. Each execution of A2 tags at least one cell, and A3 and A4 tag more. The formula has finitely many cells. Each pass of A3 ends at the right end. Each execution of A4 starts a new pass only after A3 has output one more element of the cycle, and the orbit is finite, so the cycle closes after at most passes. Hence the algorithm stops.
Cost. Let be the number of distinct names. There are passes in A3 (one for each output element, including the singleton cycles) and searches in A2, where is the number of output cycles with the singletons counted. Each pass costs a number of steps that is linear in the number of cells. So the work is of the order . Program A below makes this exact.
Program (MIX program for Algorithm A, TAOCP Program 1.3.3A). The program reads cards of 16 fields into a table of cells, one MIX word for each field. A field holds a name of up to five characters, a parenthesis or blanks. The last cell holds an equals sign that ends the input. The program runs Algorithm A on the first cells, removes the cycles of one name, writes the answer into an output area and prints it.
Node: Program 1.3.3A · Lean: not yet stated
The structure. The registers have fixed jobs. Register I3 is the cell pointer. Register I1 is the output pointer. Register X holds the value (the book calls it CURRENT) as a negative number. Register A holds the word "(" during the main work. The cell count is kept in a memory word. Cell tags are signs: after step A1 an untagged name cell holds its name as a positive number, and a tagged cell holds it as a negative number. The comparisons of the pass look only at bytes 1 to 5 of a cell, so a tagged cell still matches its name. The program has five parts.
- Setup and tagging (step A1). A loop walks over all cells once. For a "(" cell it tags the parenthesis, steps to the first symbol of the cycle (blank cells are skipped) and keeps that symbol, tagged, in register X. For a ")" cell it stores the kept symbol in its place (the closing copy). Other cells pass unchanged.
- The search of step A2. Register I3 is reset to the first cell, and the loop reads cells one at a time, looking for a cell that is untagged and not blank. If I3 reaches the end of the table, the program leaves the loop for the output.
- The start of an output cycle. The program writes "(" and the first name, saves the name as START, and tags the cell. It then reads the symbol after it into register X. The pass continues from that point. This part runs once for each output cycle.
- The pass (steps A3 and A4). A loop compares register X with the name in the current cell. A match tags the cell and loads the next cell into X, and the loop goes on two cells further. A mismatch moves on one cell. At the end of the table, X holds the new element. If X differs from START, the program writes it to the output, resets I3 to the first cell, and starts a new pass.
- The closing (step A5). The program writes ")" and compares the word three places back in the output with "(". If they are equal, the cycle has one name, and the program moves I1 back three places. Then control goes back to the search.
After the end of the search, a short tail writes () if the output is empty, pads the output area with blanks, prints it and halts. When the answer fits on one printed line, the tail takes before the halt, and of this is a block move of 22 words (). Each further printed line adds , and an empty answer adds for the move of (). The time formulas below leave this tail out, as they leave out input and output.
The frequencies. The book names the number of runs of each part of the program by a letter, and C1 uses the same letters. The table gives each letter, the work of one run and its time in . The times use the standard MIX values: a load, a store or a comparison takes , a MOVE of words takes , and the other instructions here take .
| Letter | Work of one run | Time |
|---|---|---|
| (once) | finish the cell count and store it, reset I3 before A1, load "(" into rA, point I1 at the output area | 7 |
| A1: read a cell with its sign reversed and test it for "(" | 5 | |
| A1 at a "(": tag it, step to the next cell, load that symbol with its sign reversed into rX, test it for blank | 6 | |
| A1: test the cell for ")", step I3, test for the end of the table | 7 | |
| A1 at a ")": store the tagged first symbol in its place | 2 | |
| A2: reset I3 to the first cell | 1 | |
| A2: read a cell with its sign reversed and test for an untagged name | 3 | |
| A2: step I3, test for the end of the table | 4 | |
| open an output cycle: write "(" and the name, save START | 8 | |
| tag a cell, step I3, load the next symbol into rX as a negative magnitude, test it for blank | 6 | |
| A3: compare the magnitudes of rX and the cell, branch on a match | 3 | |
| A3: step I3, test for the end of the table | 4 | |
| end of a pass: compare rX with START | 3 | |
| write the new element, step I1, reset I3 | 4 | |
| close a cycle: write ")" and test for a cycle of one name | 6 | |
| remove a cycle of one name from the output | 2 |
The jump after the blank test of and the jump that skips a blank cell after a match run only when blank cells stand inside the formula. As in the book, the analysis assumes that the blank cells are all at the right end, after the last ")".
Correctness. Each part does one step of Algorithm A on the table. The one point that needs care is the sign. The search of part 2 sees a cell as untagged when the cell is positive, and the tagging of A1 makes every "(" and every closing copy negative, so the search finds only name cells. The pass of part 4 ignores the sign, as the step A3 of the algorithm requires. By the correctness of Algorithm A, the output is the cycle form of the product.
Analysis (the time of Program A by its frequencies, TAOCP eq. 1.3.3(7)). Leaving out input, output and the tail, Program A runs for
Node: 1.3.3-(7) · Lean: not yet stated
Explanation. Formula (7) is a weighted sum of 15 unknown counts. To use it, the counts must be tied to the data: the number of cards, the number of cycles in the input, and so on. Equations (8) to (17) make this tie with two tools. Kirchhoff's first law says that the number of times that control enters a part equals the number of times that control leaves it. The other tool is a direct reading of what a part does: a part that runs once for each "(" has a frequency equal to the number of cycles in the input. The constant 7 is the time of the five instructions that run once: , , , and .
Example. C1 ran the program on the formula (13 fields on one card, so , and the table has cells, the last two blank, and one more cell with "="). The measured frequencies are
| 12 | 3 | 12 | 3 | 4 | 31 | 28 | 3 | 7 | 52 | 55 | 5 | 2 | 3 | 1 |
and (7) gives . The run on the simulator took before the tail and before the halt, and is the tail. The output was (BC)(DE) (the names are upper case letters on the cards).
Proof. Each letter in the table counts the runs of a group of instructions that always run together, so the time of the group is its frequency times the time of one run. The sum of the 16 rows of the table is (7).
Analysis (the relations of Kirchhoff's law, TAOCP eq. 1.3.3(8)). The frequencies of Program A satisfy
Node: 1.3.3-(8) · Lean: not yet stated
Explanation. Each relation balances the flow of control into a part of the program against the flow out of it. The six relations remove six of the fifteen unknowns of (7).
Example. In the run on : , , , , and .
Proof. The loop of A1 enters part at its head and leaves through part at its end, with no other exit, so . The search is entered once after A1 and once after each closing, so . Each read of the search either finds an untagged name, which opens a cycle ( times), or passes on to the step . So . A cycle that opens is closed once, and only an open cycle is closed, so , and then . The step of the pass is entered after each failed comparison, that is times (each match leads to , and of the runs of come from a match, since of them come from the start of a cycle), and after each run of . So , which is . A pass ends in and goes on either to (a new element) or to (the closing), so .
Analysis (the number of cells, TAOCP eq. 1.3.3(9)). The loop of A1 steps over every cell of the table once, so
Node: 1.3.3-(9) · Lean: not yet stated
Explanation. Each run of moves the cell pointer by one. A "(" moves it by one more in , to step over the first symbol of the cycle. The table has cells before the final equals sign.
Example. .
Proof. In the loop of A1, the pointer I3 starts at , and the loop stops when the pointer reaches the cell count . The pointer grows only in and in , by one each time, and compares it with the count after each step. Part never moves the pointer past the end, because the first symbol of a cycle lies before its ")". So the pointer moves cells in all, and this number is .
Analysis (the number of "(" cells, TAOCP eq. 1.3.3(10)). is the number of "(" cells, which is , the number of cycles of the input.
Node: 1.3.3-(10) · Lean: not yet stated
Explanation. Part runs once for each opening parenthesis that the loop of A1 meets, and each cycle of the input has one opening parenthesis.
Example. The formula has cycles, and .
Proof. The test before is true for exactly the cells that hold "(". The loop of A1 meets every "(" cell, because steps over the cell after a "(", and that cell is a name. Every cycle of the input has one such cell, and no other cell has the word "(".
Analysis (the number of ")" cells, TAOCP eq. 1.3.3(11)). is the number of ")" cells, which is also .
Node: 1.3.3-(11) · Lean: not yet stated
Explanation. Part stores a closing copy in place of a ")", once for each cycle of the input.
Example. in the run on .
Proof. The test before is true for exactly the cells that hold ")". The loop of A1 meets every such cell, and each cycle of the input ends with one ")".
Analysis (the two counts of parentheses are equal, TAOCP eq. 1.3.3(12)). .
Node: 1.3.3-(12) · Lean: not yet stated
Explanation. This relation does not follow from Kirchhoff's law, which sees only the flow of control. It comes from the data: each cycle has one "(" and one ")".
Example. in the run on .
Proof. Both sides equal by eqs. (10) and (11).
Analysis (the number of output cycles, TAOCP eq. 1.3.3(13)). , the number of cycles of the output, with the cycles of one name counted.
Node: 1.3.3-(13) · Lean: not yet stated
Explanation. Part opens one output cycle each time it runs. By eq. (8), , so the closing part runs times as well.
Example. , and the product of has the three cycles .
Proof. The algorithm writes one cycle for each orbit of the product, the fixed names included, before it removes the cycles of one name. There are orbits, and each one is opened once.
Analysis (the number of tags in the passes, TAOCP eq. 1.3.3(14)). , the number of name cells of the input.
Node: 1.3.3-(14) · Lean: not yet stated
Explanation. The quantity counts the nonblank fields of the input, the parentheses included. Each cycle has two parentheses, so the name cells number . Part tags one name cell each time it runs.
Example. and , so . Indeed has seven name cells (), and the run had .
Proof. The nonblank cells are the name cells and the parentheses (eqs. (10) and (11)), so there are name cells. Part runs once at the start of each output cycle, to tag the first name, and once after each match of the pass. Every name cell lies on the path of exactly one name (fact 3 of the correctness proof of Algorithm A), and it is tagged once, when the pass of that name meets it. A closing copy is never matched (fact 1), and a "(" never equals a name. So is the number of name cells.
Analysis (the number of distinct names, TAOCP eq. 1.3.3(15)). , the number of distinct names of the input.
Node: 1.3.3-(15) · Lean: not yet stated
Explanation. Each name is written to the output once, either as the first name of a cycle (in ) or as a later element (in ). A pass ends in after each of these writes.
Example. .
Proof. Each name of the input lies in exactly one orbit of the product, so it is written once, the fixed names included. The starts write names and writes the others, so . By eq. (8), and , so .
Analysis (the cycles of one name, TAOCP eq. 1.3.3(16)). , the number of cycles of one name in the output.
Node: 1.3.3-(16) · Lean: not yet stated
Explanation. Part removes each cycle of one name from the output, once.
Example. for , because is fixed.
Proof. The test before compares the word three places before the output pointer with "(". After a ")" is written, this word is "(" exactly when the cycle just closed has one name. The test runs once for each closed cycle, and it is true for the cycles of one name.
Analysis (the total number of steps of the pointer, TAOCP eq. 1.3.3(17)). The cell pointer moves cells in the search and the passes:
Node: 1.3.3-(17) · Lean: not yet stated
Explanation. After A1, the three parts , and are the only places where the pointer I3 grows. Each run of a part adds one to the pointer. Kirchhoff's law cannot give this relation, because it does not see where the pointer is, and the proof uses the meaning of the pointer. By eqs. (9) and (15), the right side is .
Example. .
Proof. The pointer is reset to the first cell in (at each search) and in (at each new pass). After a reset, the pointer travels to the cell count before the next reset. The search and the pass compare it with the count after each step, and neither loop leaves early, except at a match. A search that finds a name goes on as a pass from the same place, and a match in a pass moves the pointer twice (once in and once in ). A match never moves the pointer past the end, because the last cell of each cycle is a closing copy, which a pass never matches (fact 1 of the correctness proof of Algorithm A). So each reset is followed by exactly unit steps. The number of resets is by eq. (8).
Analysis (the running time of Program A, TAOCP eq. 1.3.3(18)). With the data quantities of eq. (19), the time of Program A, exclusive of input and output, is
Node: 1.3.3-(18) · Lean: not yet stated
Explanation. The formula is linear in , , , and , and it has one term in the product . This term dominates when the number of names and the number of cards both grow: the program makes a full pass over the table for each of the names, and the table has cells.
Example. For : , , , , , . The formula gives , the measured time. C1 also checked the formula against the simulator on 150 random formulas with up to 4 cards, with no difference.
Proof. Eqs. (8) to (16) give , , , , , , , , and . Put them into (7):
The terms in are . So the time is . By eq. (17), , so , and . The time becomes
Now and . The sum is .
Definition (the data quantities, TAOCP eq. 1.3.3(19)). For an input formula, is the number of cards, is the number of nonblank fields (the final equals sign is not counted), is the number of cycles of the input, is the number of distinct names, is the number of cycles of the output with the cycles of one name counted, and is the number of cycles of one name in the output.
Node: 1.3.3-(19) · Lean: not yet stated
Explanation. These six numbers carry all the dependence of the running time on the data. The first four describe the input, and the last two describe the answer. The numbers and are known only after the work. A bound on the time uses the facts and .
Example. Take the formula . It has 16 nonblank fields, and with the final equals sign it needs 17 fields, so , , and . Follow : the first factor sends it to , the second sends to , the third sends to , and the fourth sends to . In the same way , , and . The product is the single cycle , so and . Eq. (18) gives . The simulator measured before the tail and printed (AEDCB).
Proof. The definition is a list of names for counts. The bounds and hold because the orbits of the product partition the names and each cycle of one name is an orbit.
Algorithm (multiplication of permutations in cycle form with a table, TAOCP Algorithm 1.3.3B). Input and output are those of Algorithm A. The algorithm reads the formula once from right to left. It keeps a list of the names that it has met, and for each name in the list a table entry . After the algorithm has read a suffix of the formula, is the image of the name under the product of that suffix. A register carries a value from one symbol to the next inside a cycle. When the whole formula has been read, is the product, and the algorithm writes its cycles.
Node: Algorithm 1.3.3B · Lean: not yet stated
The idea. Let be a suffix of the formula and let be the cycle just before it. The product of the longer suffix is the cycle followed by . A name with goes to in the cycle, and then to in . The name goes to and then to . The names outside the cycle are unchanged. So the new table is for , and . A right-to-left reading of the cycle can make this change with one pass and one register: read , then , down to . At each name, put the old content of the register into the entry of the name and take the old entry into the register. The first entry that is changed (the entry of ) has no value to receive, so the algorithm puts a hole there and fills the hole at the end with the value of .
The steps. In the steps, the list of names is , with in order of first arrival, and is the length of . The symbol means "no value" ( values are always at least ).
B1. s <- 0. Set the reading position to the right end of the formula.
B2. Read the next symbol from the right. If the formula is exhausted, go to B6.
If the symbol is ")", set Z <- 0 and hole <- 0 and repeat B2.
If the symbol is "(", go to B5.
Else the symbol is a name; go to B3.
B3. Find j with L[j] = name. If no j exists, set s <- s+1, L[s] <- name,
T[s] <- s, and j <- s.
B4. Swap: t <- T[j], T[j] <- Z, Z <- t. If the old Z was 0, set hole <- j.
Go to B2.
B5. T[hole] <- Z. Go to B2.
B6. For m = s, s-1, ..., 1: if m is unmarked and T[m] != m, write a cycle
starting at m: follow m, T[m], T[T[m]], ... writing L[.] and marking
each, until the start returns. Write "(" before and ")" after.
A worked run. The formula is again. The algorithm reads from the right. The list grows as (so the names have the numbers , , , , ). The rows show (a 0 is a hole, and a blank is a name not yet in the list) and after each symbol.
| Symbol read | after | after |
|---|---|---|
) |
0 | |
| 1 | 0 | |
| 2 | 0, 1 | |
( |
2 | 2, 1 |
) |
0 | 2, 1 |
| 3 | 2, 1, 0 | |
| 4 | 2, 1, 0, 3 | |
( |
4 | 2, 1, 4, 3 |
) |
0 | 2, 1, 4, 3 |
| 5 | 2, 1, 4, 3, 0 | |
| 4 | 2, 1, 5, 3, 0 | |
| 3 | 2, 1, 5, 4, 0 | |
( |
3 | 2, 1, 5, 4, 3 |
Check the rows of the last cycle . After ), the register is . The name has number . It is new, so . The swap gives and , and the hole is . The name has number with (before this row, held the image of under the suffix , which is , number ). The swap puts into and takes into . The name (number ) has before the swap (under the suffix, , number ), and the swap puts into and takes into . At (, . The final table is . Its cycles, by the list , are: (that is ), (that is ), and is fixed (). The product is , the same as the answer of Algorithm A. The output step starts from (the name ) and writes , skips (fixed) and (marked), starts at and writes , and skips . The written form is .
Correctness. Claim: after B4 or B5 has handled all symbols of a suffix , is the image of under the product of for every name in the list, except for the entries in the cycle that is being read, where the claim holds after B5. The proof is by induction on the number of symbols read. For a name not yet in the list, the product of the suffix is the identity on it, and B3 sets , which is the identity. For a cycle read from the right, the symbols are met in the order . Let be the table before the cycle. When is read, , so B4 sets , takes and records the hole . When is read for , B4 sets (by induction on from down) and takes . At the "(", , and B5 sets . Hence the new table is and , as the idea requires. Names outside the cycle are not touched. A name that is read for the first time inside the cycle gets (the identity) in B3, which is the correct image under the empty suffix. One check is the case : , , then B5 sets , and nothing changes. At the end of the formula is the product of the whole formula, and the cycle writing of B6 is the construction of the proof of the cycle form from the table.
Termination. B2 reads one symbol each time and the formula is finite. B3 searches a finite list. B6 marks at least one entry in each cycle that it writes, and the loop on is finite.
Cost. The algorithm does a constant amount of work for each symbol, plus the search of B3. The search takes at most the length of the list. So the time is linear in the length of the formula when the names are small numbers (no search), and it is at most the length times when the names must be looked up. Program B has the exact count.
Program (MIX program for Algorithm B, TAOCP Program 1.3.3B). The program takes the same card input as Program A. It reads the table of cells from the right end to the left end. A search of the list of names uses a sentinel at the head of the list so that the loop has only one test.
Node: Program 1.3.3B · Lean: not yet stated
The structure. Register I2 is the reading position and it counts down. Register X is (a value carried in a cycle). Register I3 is , the length of the list. Register I4 is the search index and, after the search, the number of the name. Register I1 is the hole. The list of names is the array X and the table is T. The five parts are as follows.
- Fetch. The program decreases I2 and loads the cell. A blank cell ends the cycle part (it only advances the loop). A ")" resets register X to . A "(" stores the register in the hole.
- Search. For a name, the program stores it at the head of the list (the sentinel), and loops down the list from the top until the name matches. A match at the head means that the name is new.
- Insert. A new name gets the next number, and its table entry is set to the number itself.
- Rotate. The program loads the old table entry, stores register X in its place, and moves the old entry into register X (a rotation of rA and rX by five bytes does this swap in one instruction). If the old value of X was , the program remembers the number as the hole.
- Write. After the last cell, a loop on from down to writes the cycles by following and marks the written names in the list by changing their sign.
The groups and their times. As in Program A, the instructions are grouped by equal frequency. Let , let be the number of names in the input, and let be the number of steps of the search loop. The table gives each group, its time in for one run and the frequency.
| Group | Work | Time | Frequency |
|---|---|---|---|
| setup | start | 2 | 1 |
| restart at ")" | 1 | ||
| fetch | decrease position, load cell, test blank | 4 | |
| test ")" | compare and branch | 3 | |
| test "(" | compare and branch | 3 | |
| search set up | set the index and the sentinel | 3 | |
| search step | one step of the loop | 4 | |
| search result | test whether found | 1 | |
| new name | increase , store name and table entry | 6 | |
| rotate | swap of the table entry and | 7 | |
| hole | remember the hole | 2 | |
| left parenthesis | store at the hole | 2 | |
| continue | test the position | 1 | |
| output set up | pointer and test for | 2 | 1 |
| output loop test | load mark, test | 3 | |
| fixed test | compare with | 3 | |
| cycle open and close | write "(" and ")" | 6 | |
| cycle body | one name written and marked | 10 | |
| step down | decrease and test | 2 |
C1 ran the program on : , , , , , , , and the search made steps. The program wrote (CB)(DE). It ran for up to the end of the output loop, and for up to and including the halt, since the output tail is the one of Program A (, then the halt). The sum of the table is , as measured.
Correctness. The program follows the steps of Algorithm B. The sentinel makes the search loop safe: the name is stored at the head of the list before the loop, so the loop ends at the latest at the head, and a match at the head means "not found". The operations on registers do what the steps say, with the one instruction that swaps rA and rX. The output loop visits . It skips a name whose mark is set and a fixed name (). For a name that is neither, it writes the whole cycle that follows and marks each of its names, so a cycle is written once. By the correctness of Algorithm B, the output is the cycle form of the product.
Analysis (running time of Program B, TAOCP exercise 1.3.3-10 and the text of Program B). The time of Program B, exclusive of input and output, is given below. The symbols are from eq. 1.3.3(19), and is the number of steps of the search loop; the search steps satisfy with . The time is
Node: 1.3.3-anal-progB · Lean: not yet stated
Explanation. The first part of the time is the fetch of every cell of the table and is proportional to the number of cards. The second part is the work for every name, and the term with is the cost of the search. If a program uses an index directly (the names are numbers), then is not needed. The term is at most , because gives . Program A has exactly as its leading term, so for large and Program B is faster by a factor of at least in the worst case, and the factor is much larger when the average search is short.
Example. On : , , , , , , . The formula gives , as measured. For the same formula, Program A takes . The relation reads .
Proof. The frequencies follow from the structure. Each of the cells is fetched once. A cell is blank, ")" , "(" or a name. The nonblank cells number and the test for ")" runs for each of them. The ")" cells number , so the test for "(" runs times. The "(" cells number , so the names number . The search runs once for each name. A name is new once for each distinct name, which is times. The rotate group runs once for each name. The hole is recorded once for each cycle (the first name that is read after a ")" finds ), so it runs times, and the "(" group runs times. The continue group is reached from a blank cell ( times) and from a "(" ( times). The output loop tests each of the names once (the loop on has one entry for each name). The test for a fixed name runs for each unmarked name, which is once for each cycle of (the number of cycles, singletons included). Of these, are fixed, so cycles are written. Each of the names in a written cycle is written once. Add the group times:
The constants are . The terms in : . The terms in : . The terms in : . The terms in are . The terms in : . The terms in and : and . So the total is . With , . For the bounds on : a search for a name that sits at place of a list of length takes steps, and a search for a new name takes steps with . Every search takes at least one step and at most steps, so .
Definition (the inverse of a permutation, TAOCP Section 1.3.3). For a permutation , its inverse is the unique permutation with for all . In the two-line form, exchange the two rows. In the cycle form, reverse the order of the names in each cycle.
Node: 1.3.3-def-inverse · Lean: not yet stated
Explanation. The inverse undoes the permutation, so (first , then ) is the identity, and so is . The map is its own inverse. The inverse of a product reverses the order: . In Mathlib the inverse of σ : Equiv.Perm α is σ⁻¹, and Equiv.Perm.inv_def says that it is the inverse equivalence σ.symm.
Example. The permutation has the inverse , which is the same as . Check: and the inverse sends to . Also and the inverse sends to . For the array form on , take the arrangement (that is , , , ). The inverse has , , , , which is . In cycle form, and , the reversed cycle.
Proof. The inverse of a bijection is a bijection, and it exists and is unique. The two-line rule: the column becomes . For the cycle rule, if has the cycle , then for and , which is the cycle , the reversed one. For the product, applied after gives .
Algorithm (inverse in place, with signs as marks, TAOCP Algorithm 1.3.3I). Input: an array that holds a permutation of with . Output: the same array with . The algorithm needs only a constant number of extra variables. It marks the entries that belong to a cycle that has been treated by a negative sign.
Node: Algorithm 1.3.3I · Lean: not yet stated
The idea. The algorithm treats the cycles one at a time, starting each from its largest name (it uses and a cycle is treated at its largest name, because the larger names have been treated before). Take a cycle . The inverse has . The algorithm walks the cycle once. At each name , it replaces by the previous name with a minus sign, so . This is possible without losing information because the next name has been read into a variable before the entry is overwritten. At the end, the entry of gets its final value with a plus sign. The other entries of the cycle keep the minus sign, and the loop on flips the sign back to plus when it reaches each of them, because they are smaller than .
The steps.
I1. m <- n, j <- -1.
I2. i <- X[m]. If i < 0, go to I5.
I3. X[m] <- j, j <- -m, m <- i, i <- X[m].
I4. If i > 0, go to I3. Else i <- j.
I5. X[m] <- -i.
I6. m <- m - 1. If m > 0, go to I2.
A worked run. Let (), with the cycles . The inverse is . The table shows the array after each execution of I5 (the value of is the value when I5 runs; for the cycle is rewired).
| at I2 | Array after I5 | What happens |
|---|---|---|
| 7 | the cycle of 7 is rewired; gets 2 | |
| 6 | , so the sign is flipped | |
| 5 | flip | |
| 4 | the cycle is rewired at its largest name 4 | |
| 3 | the fixed point 3 gets again | |
| 2 | flip | |
| 1 | flip |
The first row in detail: For : . I3: , , , . I4: , so I3 again: , , , . Again: , , , . Again: , , , . I4: , so . I5: . The array is .
Correctness. Take the moment when the algorithm treats a cycle at its largest name (all names larger than belong to treated cycles and have final values with a plus sign, and the entries of the names smaller than in treated cycles have minus signs, or have been flipped to plus). Since , the algorithm enters I3. In the pass through I3, the variables are as follows. At the first run, where is some negative value, , , and . At the -th run, , , , . The run continues while . The entries for are positive until they are overwritten (names of the cycle that is not yet treated, never touched), and the entry of is the negative value after the first run, so the test fails exactly when has come back to (the cycle is closed) and . At that point . So , and I5 sets . The entries of are , which are the negatives of their inverse values. The loop on meets each of them later (they are smaller than ) with , and I5 sets , the final value. For a fixed point : I3 sets , , , ; then and I5 gives . A name larger than all the others of the cycle is because the loop meets the names in decreasing order and every name of the cycle is untreated until its cycle is reached. At the end every cycle has been treated, so .
Termination. The loop on goes from down to . Each I3 run advances along a cycle, and the cycle is finite and closes by the sign test. Hence the algorithm stops.
Cost. The loop of I2 runs times. The run of I3 happens once for each name: each name is visited once on its cycle. I5 runs times. The algorithm does a constant amount of work for each name, plus a constant amount for each cycle (the step ). The time is of the form , where is the number of cycles.
Program (MIX program for Algorithm I, TAOCP Program 1.3.3I). The program holds in rI1 and in rI3. Register I2 holds , not : the program loads with its sign reversed. Then the test of I2 is a jump on a positive rI2, the test of I4 is a jump on a negative rI2, and the store of I5 writes with no extra work. The array is at X with at X+1. The program has four parts: a loop head that loads and tests its sign; the body of I3 and I4 (one store, two enter instructions, one load with the sign reversed, and the jump of I4); the change , which is one enter instruction; and the store of I5 with the loop control of I6.
Node: Program 1.3.3I · Lean: not yet stated
The groups and the time. The groups are: setup (, once); load and test of I2 (, times); the body of I3 and I4 (, once for each name, so times in total); the change (, once for each cycle, times); the store of I5 (, times); and the loop control (, times). So the time is
Explanation. The constant is the sum of the four groups that run times. The halt is not counted.
Example. For , and , so . A MIX simulator gave before the halt. C1 also ran the program on 300 random permutations of 1 to 9 names. In each case the array became the inverse and the time was exactly .
Proof. The load-and-test group is the head of the loop, entered for each , so times. The body of I3 runs once for each name of each cycle, which is times in all, because the cycles partition the names. The step is made at I4 when the cycle closes, once for each cycle. The group of I5 and the loop control run once for each value of . Add: .
Algorithm (inverse in place by chains, TAOCP Algorithm 1.3.3J). Input and output are those of Algorithm I. The algorithm first negates every entry. Then it treats the names from down to . For each it follows a chain of positive entries until it finds a negative entry, and it uses the chain to put at the position and to repair the link of the chain.
Node: Algorithm 1.3.3J · Lean: not yet stated
The idea. After a name has been treated, the entry at must hold with a plus sign. The inverse of the permutation restricted to the names not yet treated is not a stored array, so the algorithm keeps it as a chain: a positive entry says "the name comes before " and links to . The negative entries mark the heads of the chains. To treat , the algorithm follows the chain that starts at until it finds a head, and then it splices the name out of the heads, writing at .
The steps.
J1. For k = 1..n: X[k] <- -X[k]. Set m <- n.
J2. j <- m.
J3. i <- X[j]. If i > 0, set j <- i and repeat J3.
J4. X[j] <- X[-i]. X[-i] <- m.
J5. m <- m - 1. If m >= 1, go to J2.
A worked run. Take the same . After J1 the array is . The table gives the number of runs of J3 and the array after J4 for each .
| Array after J4 | ||
|---|---|---|
| 7 | 1 | |
| 6 | 2 | |
| 5 | 3 | |
| 4 | 1 | |
| 3 | 1 | |
| 2 | 4 | |
| 1 | 2 |
Check the first rows. For : , at once. J4: and . For : , , so , and . J4: and . The final array is the inverse . The total number of runs of J3 is .
Correctness. Let be the inverse (not stored). Let be the names that have been treated at the start of the iteration for , let , and let be the map that sends to the first of that lies in . The map is a permutation of (it is the permutation with the names of spliced out of its cycles). Invariant: at the start of the iteration for , for every , and for every .
The invariant holds at the start. When , is empty, is the whole set, , and J1 has made . Suppose that it holds for . Names have positive entries. The names in have negative entries. In J3 the chain goes from to as long as , because then . The chain stops at the first . It stops, because the chain would return to only by passing through with , which is false. Let be the number of steps, so . The names are in for (each is a step of the chain), except that itself. So the next name of the cycle after these that is in is , which is in because . Hence . (For , and directly.) At J3 the final , so . J4 does two things. It sets , and it sets . The new sets are and , and is with spliced out: and for all other . So , the entries of the other names of are unchanged and equal to , and gives the new case of the first part. The case (the chain ends at the name that is removed) is covered by the order of the two stores: the first store changes nothing and the second sets . After the iteration for , is the full set, is empty, and for all , which says .
Termination. The chain of J3 stops after at most steps, as shown above. The loop on has iterations.
Cost. The loop of J3 has runs for the name , and the total is the unknown. The rest of the work is a constant for each name. Program J has the exact time, and the average of is derived below.
Program (MIX program for Algorithm J, TAOCP Program 1.3.3J). The first loop negates the entries with a store of the sign field only. The second loop is the main loop on (in rI1). The chain loop of J3 has three instructions: a negation of the pointer, a load of the next entry with the sign reversed, and a test of the sign. The final part of the body of the main loop has three transfers (load, store, store) and the loop control.
Node: Program 1.3.3J · Lean: not yet stated
The groups and the time. The setup and the negation loop take units. The main loop has one setup (, once), a head ( for each ), the chain loop ( for each run, runs in all), a body of load, store, store ( for each ) and a loop control ( for each ). So
Example. For , and , so . A MIX simulator gave before the halt. On the same 300 random permutations as for Program I, the array became the inverse and the time was exactly , with counted by the simulator.
Proof. The negation loop takes : to set the index, and for each entry for its three instructions (a store of the sign, , an increment and a jump, each). The main loop adds . The sum is .
Analysis (the running time of Programs I and J, TAOCP exercise 1.3.3-14 and the text). With the number of cycles, the time of Program I is , and the time of Program J is . For a random permutation, the average of is , and the average of is . So the average times are
Node: 1.3.3-anal-progIJ · Lean: not yet stated
Explanation. Program I runs in time that is linear in on average (and in the worst case, as ). Program J has a term in , because the chain of the name has average length about , and the sum of is . Program J has the shorter loop body, but the chains are costly for large .
Example. The average times for several are:
| Program I | Program J | J / I | |
|---|---|---|---|
| 10 | 144.93 | 220.87 | 1.52 |
| 100 | 1407.19 | 2997.70 | 2.13 |
| 1000 | 14009.49 | 38973.83 | 2.78 |
| 10000 | 140011.79 | 481545.39 | 3.44 |
For the exact average of is , found by running Algorithm J on all permutations. The formula gives . The exact averages for from the complete enumeration are , and they equal .
Proof. The count for Program I is proved above, and the mean of is by eq. (21) below. For : the name costs runs of J3, and (the chain stops at the first with , because means ). For a uniform random , is uniform. The event means that all exceed . These values are distinct (a repeat would need , which is not greater than ), and they are names among the names above . The number of such is : choose the ordered values, then complete the partial injection. So , which equals . Put . Then Use (both sides equal ). The sum becomes . With the sum is (parallel summation, eq. 1.2.6(10)). So . Then . Insert in : .
Definition (canonical cycle form, TAOCP eq. 1.3.3(20)). The canonical cycle form of a permutation lists all cycles, the singletons included. Inside each cycle, the smallest name is written first. The cycles are written in decreasing order of their first names. Write a permutation of in this form and delete the parentheses. The result is a linear arrangement of , and the map from permutations in cycle form to arrangements is a bijection. The cycles of the permutation correspond to the left-to-right minima of the arrangement.
Node: 1.3.3-(20) · Lean: not yet stated
Explanation. A left-to-right minimum of an arrangement is an entry that is smaller than all entries before it (the first entry is always one). In a canonical form the first name of each cycle is smaller than all names of the earlier cycles and of its own cycle, so it is a left-to-right minimum. The other names of a cycle are larger than the first name of their own cycle, and that name stands before them, so they are not minima. To go back, put a "(" before each left-to-right minimum and a ")" before each "(" except the first, and at the end.
Example. Take . Rotate each cycle so that the smallest name comes first: . Sort the cycles by decreasing first name (): . Delete the parentheses: . The left-to-right minima of this arrangement are : three cycles. To go back from , put "(" before , and and get . A second example reads an arrangement as a permutation again: the arrangement has minima , so it comes from . As a permutation of (, , and so on) it has the cycle form .
Proof. Let be written in canonical form. Take the first name of a cycle. Every name before it belongs to an earlier cycle. In an earlier cycle with first name , the name is the smallest of its cycle, and by the order of the cycles, so every name of the earlier cycle exceeds . Hence is a left-to-right minimum. A name that is not first in its cycle is larger than the first name of its cycle, which stands before it, so is not a minimum. Hence the minima are exactly the first names, and the cycles can be recovered by cutting before each minimum. Conversely, take any arrangement and cut it before each minimum. Inside a piece, the first name is the running minimum and all other names are larger than it, so the first name is the smallest of the piece. The first names of the pieces decrease from left to right because each is a new running minimum. So the pieces form a canonical cycle form. The two maps are inverse to each other, so the correspondence is a bijection between the permutations and the arrangements.
Theorem (the number of cycles of a random permutation, TAOCP eq. 1.3.3(21)). The number of cycles of a permutation of names (singletons counted) has the minimum , the maximum , the mean and the variance , where . The number of permutations with cycles is the Stirling number of the first kind , and .
Node: 1.3.3-(21) · Lean: not yet stated
Explanation. By the bijection of (20), the number of cycles is the number of left-to-right minima of a random arrangement. Section 1.2.10 has the same statistic for the right-to-left maxima. The answer is a sum of independent random variables: the -th is with probability and otherwise. So the mean is , and the variance is . The number of cycles has no large spread: its deviation is about .
Example. The counts by exhaustive enumeration are:
| mean | variance | |||||||
|---|---|---|---|---|---|---|---|---|
| 3 | 2 | 3 | 1 | |||||
| 4 | 6 | 11 | 6 | 1 | ||||
| 5 | 24 | 50 | 35 | 10 | 1 | |||
| 6 | 120 | 274 | 225 | 85 | 15 | 1 |
For , and . The total number of cycles of the 24 permutations of 4 names is , which equals .
Proof. Let be the number of arrangements of with left-to-right minima. Build an arrangement of names from one of names by putting the name in one of the places. The name is a minimum only at the front, because it exceeds every other name. A name that is not keeps its status (it is a minimum or not) when is inserted, because is larger than all names and does not change any running minimum. So the front insertion gives minima from , and each of the other insertions keeps . Hence , with . By the bijection of (20) the number of permutations with cycles obeys the same recurrence, which is the recurrence of the Stirling numbers of the first kind. For the generating function the recurrence says and , so . Dividing by , the probability generating function is . The factor is the generating function of a variable that is with probability and otherwise. The mean of such a variable is and its variance is . The product of generating functions is the generating function of the sum of independent variables, and means and variances add. So the mean is and the variance is . The minimum is (the arrangement has the one minimum , and every arrangement has at least the first entry as a minimum) and the maximum is (the arrangement ).
Definition (permutations with exactly fixed names, TAOCP eq. 1.3.3(22)). For , the symbol counts the permutations of names with exactly singleton cycles, that is, fixed names. The number is the number of derangements of names. Then
Node: 1.3.3-(22) · Lean: not yet stated
Explanation. A permutation with exactly fixed names is made in two steps. Choose the names that stay fixed. Then permute the other names with no fixed name.
Example. The counts for are (by exhaustive enumeration) : ; : . Check and .
Proof. A permutation with exactly the fixed set () is the identity on and a permutation with no fixed name on the rest. The map that restricts the permutation to the rest is a bijection from the permutations with fixed set to the permutations of the other names with no fixed name. There are sets and each gives permutations. The sets are different, so the permutations that they give are different.
Equation (the sum rule, TAOCP eq. 1.3.3(23)). Every permutation has some number of fixed names, so
Node: 1.3.3-(23) · Lean: not yet stated
Explanation. The permutations are sorted by their number of fixed names. Note that for , because fixed names force the last name to be fixed too.
Example. For : . For : .
Proof. Each permutation has exactly one number of fixed names, so it is counted in exactly one .
Equation (the derangement identity, TAOCP eq. 1.3.3(24)). Put . Then for every ,
Node: 1.3.3-(24) · Lean: not yet stated
Explanation. This is eq. (23) after the substitution of eq. (22): , and . Written with falling powers, .
Example. With : for , .
Proof. In (23), put and use .
Equation (the number of derangements, TAOCP eq. 1.3.3(25)). For every ,
Node: 1.3.3-(25) · Lean: not yet stated
Explanation. The probability that a random permutation of names has no fixed name is a partial sum of the series for . It converges to very fast: the error after terms is less than .
Example. for is . Check: .
Proof. Identity (24) determines the numbers one after the other: the term is and the other terms involve only with . So there is at most one sequence that satisfies (24) for all , and it is enough to check that satisfies it. Compute , because . Put . The double sum runs over pairs with and has the terms . Group by : . So the sum is . The inner sum is , which is for and for . So the double sum is and the whole is . Hence .
Equation (the distribution of the fixed names, TAOCP eq. 1.3.3(26)). The probability that a random permutation of names has exactly fixed names is
Node: 1.3.3-(26) · Lean: not yet stated
Explanation. For fixed and large , , the Poisson distribution with mean .
Example. For : , , , , , . The formula gives for : , and for : .
Proof. By (22), , and by (25) the last fraction is the partial sum.
Equation (the generating function of the fixed names, TAOCP eq. 1.3.3(27)). The generating function is
Node: 1.3.3-(27) · Lean: not yet stated
Explanation. The sum is the start of the series of , which is the generating function of the Poisson distribution with mean .
Example. . This says that of the two permutations of two names, one has no fixed name (probability ) and one has two (probability ), which is right. , so , , , (the counts of 6).
Proof. Expand (the binomial theorem and ). Sum over . The coefficient of is . With it is , which is by (26).
Equation (the statistics of the fixed names, TAOCP eq. 1.3.3(28)). For , the number of fixed names has the minimum , the mean , the maximum and the variance (deviation ). For the mean is and the variance is .
Node: 1.3.3-(28) · Lean: not yet stated
Explanation. The mean and the variance do not depend on for . A random permutation has one fixed name on average, whatever its size.
Example. For : the counts are for . The mean is . The second moment is , so the variance is . For the same computation from the counts of eq. (22) gives mean and variance .
Proof. From (27), . The generating function of a probability distribution has , the mean and . Hence , the mean is for , and for . So and the variance is . For , , since , so and the variance is . The minimum is for , because (by (25), , as the partial sums of the alternating series with decreasing terms are positive for ; the example is a derangement). The maximum is (the identity).
Theorem (the principle of inclusion and exclusion, TAOCP eq. 1.3.3(29)). Let be subsets of a set of elements. The number of elements that lie in none of the sets is
Node: 1.3.3-(29) · Lean: not yet stated
Explanation. The first sum removes the elements in a set, but it removes twice the elements that lie in two sets. The second sum puts these back, and so on. Each term of the series adds or removes the elements that lie in a given number of sets.
Example. Count the permutations of with no fixed name. Let be the set of permutations that fix . Then , (three sets), (three pairs), . The count is , the two derangements and . In general, and there are choices, so the number of derangements is , in agreement with (25).
Proof. Take an element that lies in exactly of the sets. It is counted once in . It is counted times in the sum of the intersections of sets, because it lies in exactly the intersections of sets chosen among its sets. So the total contribution of is , which is for and for . So the sum counts the elements with once, and no other element.
The exercises
The table has the exercises of Section 1.3.3. The kind is the class of spec 06.3 that C1 proposes, and the indexer of S0 fixes it in the map.
| Exercise | Rating | Markers | Kind | Lean | Solution |
|---|---|---|---|---|---|
| 1.3.3-1 | 2 | K3 | not yet stated | X1, 1.3.3-1 | |
| 1.3.3-2 | 10 | K5 | not yet stated | X1, 1.3.3-2 | |
| 1.3.3-3 | 3 | K3 | not yet stated | X1, 1.3.3-3 | |
| 1.3.3-4 | 10 | K3 | not yet stated | X1, 1.3.3-4 | |
| 1.3.3-5 | 10 | M | K3 | not yet stated | X1, 1.3.3-5 |
| 1.3.3-6 | 28 | M | K7 | not yet stated | X1, 1.3.3-6 |
| 1.3.3-7 | 10 | K3 | not yet stated | X1, 1.3.3-7 | |
| 1.3.3-8 | 23 | K2 | not yet stated | X1, 1.3.3-8 | |
| 1.3.3-9 | 10 | K2 | not yet stated | X1, 1.3.3-9 | |
| 1.3.3-10 | 28 | M | K7 | not yet stated | X1, 1.3.3-10 |
| 1.3.3-11 | 15 | K5 | not yet stated | X1, 1.3.3-11 | |
| 1.3.3-12 | 27 | M | K5 | not yet stated | X1, 1.3.3-12 |
| 1.3.3-13 | 24 | M | K1 | not yet stated | X1, 1.3.3-13 |
| 1.3.3-14 | 34 | M | K7 | not yet stated | X1, 1.3.3-14 |
| 1.3.3-15 | 12 | M | K3 | not yet stated | X1, 1.3.3-15 |
| 1.3.3-16 | 15 | M | K3 | not yet stated | X1, 1.3.3-16 |
| 1.3.3-17 | 24 | M | K1 | not yet stated | X1, 1.3.3-17 |
| 1.3.3-18 | 27 | M | K3 | not yet stated | X1, 1.3.3-18 |
| 1.3.3-19 | 21 | HM | K1 | not yet stated | X1, 1.3.3-19 |
| 1.3.3-20 | 20 | M | K3 | not yet stated | X1, 1.3.3-20 |
| 1.3.3-21 | 22 | M | K3 | not yet stated | X1, 1.3.3-21 |
| 1.3.3-22 | 34 | HM | K1 | not yet stated | X1, 1.3.3-22 |
| 1.3.3-23 | 42 | HM | K7 | not yet stated | X1, 1.3.3-23 |
| 1.3.3-24 | 41 | M | K7 | not yet stated | X1, 1.3.3-24 |
| 1.3.3-25 | 22 | M | K1 | not yet stated | X1, 1.3.3-25 |
| 1.3.3-26 | 24 | M | K3 | not yet stated | X1, 1.3.3-26 |
| 1.3.3-27 | 20 | M | K3 | not yet stated | X1, 1.3.3-27 |
| 1.3.3-28 | 21 | M | K3 | not yet stated | X1, 1.3.3-28 |
| 1.3.3-29 | 25 | M | K1 | not yet stated | X1, 1.3.3-29 |
| 1.3.3-30 | 24 | M | K3 | not yet stated | X1, 1.3.3-30 |
| 1.3.3-31 | 38 | HM | K1 | not yet stated | X1, 1.3.3-31 |
| 1.3.3-32 | 25 | M | K3 | not yet stated | X1, 1.3.3-32 |
| 1.3.3-33 | 33 | M | K1 | not yet stated | X1, 1.3.3-33 |
| 1.3.3-34 | 25 | M | K5 | not yet stated | X1, 1.3.3-34 |
| 1.3.3-35 | 30 | M | K5 | not yet stated | X1, 1.3.3-35 |
| 1.3.3-36 | 27 | K6 | not yet stated | X1, 1.3.3-36 | |
| 1.3.3-37 | 26 | M | K1 | not yet stated | X1, 1.3.3-37 |
The order to do them: 1.3.3-1 to 5 first, to get used to cycle form and the product (exercise 2 does a rearrangement with exchanges instead of assignments). Exercises 1.3.3-6 and 7 train the cost analysis of Program A, and 1.3.3-10 does the same for Program B; the analysis of Program B above gives its formula. Exercises 1.3.3-8 and 9 compare Algorithms A and B: whether B can read from the left, and whether the two outputs agree exactly. Exercise 1.3.3-11 asks for the rule that inverts a permutation in cycle form, and 1.3.3-12 transposes a rectangular matrix in place. Exercise 1.3.3-13 is the proof of Algorithm J, which the chapter gives in full, 1.3.3-14 is the average of , and 1.3.3-24 asks for its variance. Exercises 1.3.3-15 and 16 use the canonical form. Exercises 1.3.3-17 to 23 go further into the statistics of cycles and fixed names. Exercises 1.3.3-25 to 27 treat inclusion and exclusion. Exercises 1.3.3-28 to 31 study the Josephus permutation in cycle form, 1.3.3-32 and 33 build permutations from products of transpositions and of fixed sequences, 1.3.3-34 to 36 move blocks of data in place, and 1.3.3-37 is about even permutations.
Lean
The Lean code of tamnd/taocp-lean at main has no declaration for the algorithms and programs of Section 1.3.3, so each Node line of this chapter says "not yet stated". Mathlib has the following objects.
- Permutations:
Equiv.PermwithEquiv.Perm.one_applyandEquiv.Perm.inv_def. The theoremEquiv.Perm.mul_applygives , so the product of Mathlib acts from right to left. The product of this chapter acts from left to right, so a Lean form of eq. 1.3.3(1) to (6) swaps the factors. - Cycles:
Equiv.Perm.cycleTyperecords the cycles of length at least two, andEquiv.Perm.cycleType_eq_zerosays that it is empty for the identity only.Equiv.Perm.sum_cycleTypegives the sum of the lengths,Equiv.Perm.cycleOfthe cycle through a point andEquiv.Perm.SameCyclethe relation of lying in one cycle.Equiv.Perm.card_fixedPointscounts the fixed points. - Derangements:
derangements,mem_derangements_iff_fixedPoints_eq_empty,numDerangements,numDerangements_add_two,numDerangements_succ,numDerangements_sum,card_derangements_eq_numDerangementsandcard_derangements_fin_eq_numDerangements. They cover eq. 1.3.3(24) and (25). - Stirling numbers:
Nat.stirlingFirstandNat.stirlingFirst_succ_succin Mathlib, andTAOCP.stirling1,TAOCP.stirling1_succ_succandTAOCP.harmonicPowin taocp-lean. Mathlib has no theorem that counts the permutations of points by their number of cycles, so eq. 1.3.3(21) has no Lean form yet. - Inclusion and exclusion:
Finset.inclusion_exclusion_card_biUnionandFinset.inclusion_exclusion_card_inf_complfor eq. 1.3.3(29), andharmonicfor .
Notes and history
Cycle notation and the product of permutations are older than the machine algorithms of this section. The section uses them to show how a program can work on symbolic data with one pass or with a table. The two algorithms trade time for space: Algorithm A needs no table and runs in time proportional to the square of the input size in the worst case, and Algorithm B needs a table and runs faster.
The inverse in place has a long literature. The book credits Algorithm I to B.-C. Huang (1981) and Algorithm J to J. Boothroyd. The analysis of the chain length of Algorithm J gives , a case where a harmonic number appears from a simple expected value.
The numbers are named after J. Stirling, who studied them in the Methodus differentialis (1730). Inclusion and exclusion appears in the Doctrine of Chances of A. de Moivre (1718). The matching problem, which asks for the chance that a permutation has no fixed point, was studied by P. R. de Montmort a few years earlier.
Section 1.3.3 of TAOCP uses permutations as the subject of four MIX programs and as the subject of two short analyses. It first shows how to write a permutation as a set of cycles and how to multiply two permutations. It then gives two algorithms that turn a product of cycles into disjoint cycles, one that scans the input many times and one that scans it once, and a MIX program for each. Then it builds two algorithms that invert a permutation inside its own array, again with a MIX program for each. It ends with the statistics of random permutations: the number of cycles has the mean , and the number of fixed points has mean and variance . This chapter of C1 explains each item of the section, proves each claim in full, and checks each count and each time on a small input that C1 runs.
The source of this page. Something is wrong? Report it.