Chapter 7: Permutations
Exercise 7.1 🌟
All algorithms run in time without first trying to reconstruct the associated permutation.
left-to-right maxima: Traverse the inversion table from left to right and register indices where .
right-to-left maxima: If is a RTL maximum, all elements greater than must be to its left. Therefore, a smaller means the element itself is larger. By traversing the inversion table right-to-left, the RTL maxima correspond exactly to the indices where achieves a new minimum.
Initialize and an empty list.
Traverse backwards from to 1:
If , add to the list and update .
right-to-left minima: Let denote the number of elements to the left of that are smaller than . Similar to the logic above, by traversing the inversion table right-to-left, the RTL minima correspond exactly to the indices where achieves a new minimum.
Initialize and an empty list.
Traverse backwards from to 1::
If , add to the list and update .
Exercise 7.2
Let be the number of cycles in the permutation and denote by the length of the th cycle. The number of ways to write the sample permutation in cycle notation is .
For the sample permutation in Figure 7.1, we’ve equivalent ways to write it down.
Exercise 7.3
There are permutations of elements having exactly two cycles, each of length .
There are permutations of elements having exactly cycles, each of length 2. Notice that we must divide by , since for a given representation all other possible ways of "flipping" elements in those cycles are duplicates.
Exercise 7.4
We must maximize the product from Exercise 7.2 subject to the constraint . The formula depends on the number of cycles and the product of their lengths. If we increase then we reduce the lengths and vice versa. Nonetheless, the contribution of is more important, as it grows factorially.
Let’s assume that we start with an identity permutation with . This results in equivalent representations. Can we maximize this number? If we set only one cycle to length 2 and keep the others at 1, then we get for . It turns out that we cannot attain a better result.
Therefore, the identity permutation has the greatest number of different representations with cycles. For the trivial edge cases of and , all permutations have the exact same number of representations.
Exercise 7.5
The Python 3 program below implements the task in time.
It outputs 232 for the sample permutation from the book.
Exercise 7.6 🌟
Since is strictly increasing for all practical purposes, we’ve
By the probability integral transform, are independent and identically distributed (i.i.d.) uniform on . For i.i.d. uniform random variables, all orderings are equally likely by symmetry, because the joint density is symmetric. Hence,
Observe that we can easily change the relational operator, for example, from < to > and still get the same outcome. Furthermore, for i.i.d. continuous random variables, the probability of any fixed strict ordering is .
Exercise 7.7
Cycle leaders are shown in bold letters. Apparently, they’re left-to-right maxima.
Exercise 7.8
The Python 3 script below implements the original left-to-right minima based variant.
Exercise 7.9 🌟
For computing the inversion table corresponding to a given permutation, we scan the permutation left to right, maintaining a Fenwick tree over the values . When we encounter the value , we query how many values greater than have already been seen: that count is exactly . Then we mark as seen. The usage of the Fenwick tree is important to attain an efficient linearithmic algorithm, as it natively supports range sums. Recall that marking as seen is nothing else than setting 1 for that position in the range. A naive approach would result in quadratic performance.
For computing the permutation corresponding to a given inversion table, we follow the algorithm from the book and process the entries from right to left (). We maintain an array of “empty slots” that is represented as a Fenwick tree having 1 at each position that is still free. To set to be the th largest of the integers not yet used, we binary search on the Fenwick tree’s prefix sums to find the smallest position such that the number of free slots up to is . Then we mark that slot as occupied (set Fenwick tree at to 0).
Exercise 7.10
A one-to-one correspondence between permutations and lists of integers with is easy to establish. Given a permutation, its altered inversion table is such a list. The reconstruction algorithm proves the existence of the transformation in the opposite direction:
Create an array of empty slots.
Process the values from smallest to largest ().
Place into the th available empty slot from the left.
Mark the slot as occupied.
Observe that we can use the same Fenwick tree based approach, as in the previous exercise. At the start, we initialize it with 1s at all positions (representing empty slots). Using binary lifting we can find the next available free slot in time.
Exercise 7.11
There are independent ways to pick the rows and columns for rooks. Let the sequence of selected columns be . For any such sequence, we have an additional possibilities to place rooks in selected rows; choices for , choices for , and so on. A symmetrical argument applies for permuting rows. Therefore, multiplying these numbers together gives the total to be
Exercise 7.12
There are symmetries. The "above and left" gives the same number as "below and right" that equals . Furthermore, the "above and right" gives the same number as "below and left" that equals .
Exercise 7.13
An involution is its own inverse. Therefore, the original matrix (lattice representation) must equal its transpose. This is by definition a symmetric matrix.
Exercise 7.14
Exercise 7.15 🌟
Let be 3 consecutive values in a permutation. Looking at Figure 7.5, we can see that an inorder traversal of a HOT reproduces the underlying permutation. Now, based on relationships between these 3 values, we can decipher the required structural characterizations of properties of permutations:
(rise). Because is smaller it’s an ancestor of . For the inorder traversal to visit immediately after , cannot have a left child. On the other hand, must have a right child.
(fall). Because is smaller it’s an ancestor of . For the inorder traversal to visit immediately after , cannot have a right child. On the other hand, must have a left child.
(double rise). cannot have a left child, but it does have a right child, since it’s an ancestor of . Therefore, only has a right child.
(double fall). cannot have a right child, but it does have a left child, since it’s an ancestor of . Therefore, only has a left child.
Exercise 7.16 🌟
We can count such alternating permutations thankfully to bijection with HOTs. There are two types of such permutations: down-up (starts with a fall) and up-down (starts with a rise). There is a simple one-to-one correspondence between them, so it’s enough to handle one group. It turns out that down-up permutations can be nicely described using the symbolic method.
Let’s tackle the case when is odd. This can be expressed via the symbolic method
where is the class of odd-length down-up permutations represented as HOTs consisting of strictly degree 0 and degree 2 nodes. This can be seen by recalling that the inorder traversal of a HOT reestablishes the original permutation. Since we have a sequence starting with a fall, using the rules from the previous exercise, we can conclude that the border elements of a sequence must be leaves together with all the peaks. In the middle, we have valleys.
In a HOT, the root must always be the absolute minimum value. To capture this via the symbolic method, we must use a new operator, called the min-box product, that controls the relabeling process. The corresponding functional equation is
with the initial condition . The solution is .
To handle the case when is even, notice that the absolute minimum (taking up 1 node) must be the root. Picking any candidate splits the sequence into two down-up sequences of different parities (zero is regarded as even). This gives
where is the class of even-length down-up permutations represented as HOTs. The corresponding functional equation is
with the initial condition . The solution is .
Since the two cases are disjoint, the combined result is
where is the EGF for alternating permutations. The coefficients can be extracted by looking at the Taylor expansions of the constituent functions. Notice that we multiply by two to include the up-down permutations, too. Finally, because up-down and down-up permutations are indistinguishable for lengths 0 and 1, multiplying by 2 overcounts them, hence, we must subtract extra terms.
Exercise 7.17
There is only one permutation (shown in Figure 7.5) associated with the given HOT, unlike BSTs (see Exercise 7.14).
Exercise 7.18
We just need to tweak a bit the symbolic method expression from Exercise 7.16 to include nodes with a single child (either left or right). This gives
The corresponding functional equation is
with the initial condition .
Exercise 7.19
Let be the set of all permutations. For each permutation , represents the corresponding BST built from . Recall that multiple permutations may result in the same BST. Observe that the length of the given permutation determines the size of the associated BST. This gives
The binomial convolution is fully justified, because even though the left and right subtrees are split based on the value of the root (first element in ), they maintain their relative order. The number of ways to interleave those two subsequences, without impacting the final tree, is exactly driven by the binomial coefficient. This becomes clearer by changing perspectives via lattice representation of permutations, more specifically looking at Figure 7.4. As stated in the book:
Note that many permutations might correspond to the same binary search tree: interchanging columns corresponding to a node above and a node below any node will change the permutation, not the tree.
The pivot is the root of the BST (first element in the permutation). Everything above and below of it are elements comprising the subtrees. Now, the number of ways to change columns for those elements is exactly dictated by the binomial coefficient.
Differentiating both sides of the equation, as was done in the book for HOTs, we get
We can use to enumerate permutations, thus we get our differential equation
Exercise 7.20
Employing Theorem 7.1 gives 1,576,575 permutations.
Exercise 7.21
From left to right, the frequencies are: 224, 1 and 896.
Exercise 7.22
The smallest number corresponds to a chain shape. The largest number corresponds to balanced trees. The reason is obvious, since in these trees subtree sizes drop rapidly.
Exercise 7.23
The arguments are literally the same as for the direct derivation of EGF, just that we are growing larger structures from the perspective of those larger structures. As a side note, we can immediately read out this recurrence from the differential equation for the involution EGF (presented in the book) by equating coefficients for on both sides of the equation.
Exercise 7.24
This is a variation of the previous exercise. We need to add cycles of length 3 into the picture, that entails a "double loop." This gives
Exercise 7.25
Our generating function is
The radius of convergence bound is (see Section 5.5 in the book)
To minimize this, we take the derivative of its logarithm with respect to and set it to zero
This gives
Using the Stirling's approximation , we get
Exercise 7.26
Actually, in the derivation of the EGF for the number of permutations that consist only of cycles of odd length (see Exercise 5.7), we had indirectly solved this problem, too. Thus, the EGF associated with the combinatorial class is
The EGF for cycles of length divisible by is a simple generalization of even length cycles
Exponentiate to find the EGF for the permutations
Exercise 7.27
Following the instruction from the book gives
Let be the number of derangements of size . Now, we extract the coefficient of using Table 3.4 from the book
with and .
Exercise 7.28 🌟
Slow Symbolic Manipulation
The next Python 3 script uses SymPy to evaluate the EGF according to Table 7.5. Compare this method with the "manual" approach in Exercise 6.63. Nevertheless, don’t try to run this with , as it requires an eternity to finish.
Fast Combinatorial Approach
Instead of expanding the generating function, we can build the permutations directly via the proper combinatorial recurrence (see the previous exercise and Exercise 7.24). Let be the number of valid permutations of size . Consider the element . In a valid permutation, it must belong to a cycle of some length . Because of our restriction, . For any valid cycle length :
We need to pick other elements from the remaining elements. There are ways to do this.
There are ways to arrange these elements into a valid cycle.
There are ways to arrange the remaining elements into valid cycles.
Multiplying these together and summing over all possible allowed cycle lengths , gives our recurrence
The next Python 3 script employs dynamic programming and achieves stunning performance compared to the previous variant. It handles much larger problem sizes than required for this exercise.
Exercise 7.29 🌟
There are ways to form a subset of size from elements. In an arrangement, the order matters, so we must multiply this by . In other words, the product is a total number of ways to form -tuples from elements. Finally, we must sum over all . We can translate this in terms of an EGF
The RHS follows from the definition of a binomial sum of factorials (see Tables 3.3 and 3.4 in the book).
As a side note, we can also derive the EGF using the symbolic method. An arrangement takes labels and partitions them into two distinct groups:
The primary ordered group defining the -tuples of selected elements.
The leftover unordered group consisting of unselected elements.
The number of ways to distribute labels onto items is . Therefore,
Exercise 7.30
The hint gives the answer, since there is a bijection between the original permutations and their complements. Furthermore, the number of rises in a permutation equals the number of falls in its complement , and vice versa. For example, let be a rise in . It becomes a fall in q, because
Thankfully, due to this bijection, the average number of rises and the average number of falls must be identical. Their total is , so the result follows immediately.
Exercise 7.31 🌟
Exercise 7.32
We can also expand the exponential into a Taylor series
Substitute that expanded exponential back into our equation
Thus, . Again, we continue expanding terms, this time the binomial
Now substitute this back into our polynomial expression
The indices in the sums must satisfy the following equations:
Substituting we get
Exercise 7.33
The equation in this exercise is known as Worpitzky's identity. We’ve already done bulk of the work in the previous exercise. The idea is to start with and run it in "reverse" (focus on the underlined part in the expression for ).
Substituting into the binomial coefficient gives us the coefficient for the RHS
A permutation with runs has falls and rises. Based on Exercise 7.30, the number of rises equals the number of falls in a complementary permutation, so
Exercise 7.34
Instead of looking at a finished permutation and trying to find the subsequences, let's build the permutations around a specific increasing subsequence of length . This is what the book’s hint is trying to tell. To force an increasing subsequence of length to exist in a permutation of length , we make the following choices:
Pick slots out of the available positions where our subsequence will live. There are ways to do this.
Pick labels for our subsequence. There are ways to choose these values.
Because this must be an increasing subsequence, the chosen labels must be placed into the chosen slots in exactly one specific order (sorted from smallest to largest).
We have leftover labels and leftover slots. We can arrange these however we want. There are ways to place them.
Multiplying these choices together and simplifying, we get
Summing over all we get
Exercise 7.35
In the previous exercise, we’ve already found the total number of increasing subsequences of length across all permutations of length .
Now, we plug this directly into the definition of an exponential CGF
From Exercise 4.4 we get that .
Exercise 7.36
Combining the formula for the grand total (see the book) with the one from the previous exercise, we get
Observe that the average number asymptotically doesn’t depend on polynomial terms stemming from the short subsequences. This is expected, since for large , extremely small sequences are asymptotically negligible, although their numbers can be significant in an absolute sense. Therefore, the estimate from Theorem 7.6 still applies.
Exercise 7.37
According to Theorem 7.7, the average number of all mentioned node types is . The expected total storage cost is the sum of the expected costs of each node type. Therefore, the storage requirement is .
Exercise 7.38
This is a corollary of the proof given in Exercise 7.30. Namely, peaks in the original permutation turns into valleys in the complement, and vice versa. So, due to this bijection, valleys and peaks have the same distribution for random permutations.
Exercise 7.39
Based on the corollary of Theorem 6.7, the average number of leaves in a random binary Catalan tree is . Exercise 6.40 shows that the average number of unary nodes in a random binary Catalan tree is . Therefore, the average number of binary nodes is also , so the storage requirement is .
Exercise 7.40 🌟
Rises and falls depend solely on relative of order of values in a sequence. Thus, a sequence of random real numbers between 0 and 1 (uniformly and independently generated) may be regarded as a random permutation of elements. Based on the Theorem 7.7 from the book, in a random permutation of elements, the average numbers of double rises and double falls are each.
Let be a sequence of independent, uniformly distributed continuous random variables on the interval . A double fall occurs starting at index if
Because these variables are continuous and independent, the probability of any two being exactly equal is zero. Therefore, any specific triplet must fall into one of possible strict orderings. By symmetry, since they are drawn from the exact same uniform distribution, every single one of those 6 orderings is equally likely. Only exactly one of those 6 orderings is a strictly descending sequence. Therefore, the probability of a double fall occurring at any specific index is exactly 1/6.
Let be a Bernoulli random variable, with success probability , indicating if there is a double fall starting at index . There are possible starting positions, so the total expectation for the number of double falls is (due to linearity of expectations). The number of double rises follows by symmetry. This concludes the continuous-model proof of the above asymptotic result.
Exercise 7.41
We apply the symbolic method for labelled objects with parameters. We must mark any root that has a right-child (either right-branching node and/or binary node in an HOT). This gives (notice the usage of the boxed operator, see Exercise 7.16)
Differentiating both sides of the corresponding functional equation with respect to (effectively taking out the root)
Let be an abbreviated form for the EGF. We need to integrate
Using partial fractions
Since an empty tree has size 0, , which means . Thus,
Exercise 7.42
To have one inversion, exactly one pair of neighboring elements must be swapped. There are such candidate pairs.
To have two inversions, exactly two pairs must swapped, which can happen in ways. But for neighboring pairs the order of swaps also matters. This adds additional choices. So, the total is .
For three inversions, we can select 3 pairs, but for neighboring pairs the order matters. Furthermore, if we have a neighboring triplet, then the order of swaps of the first and third pairs also matters. Besides, we can also pick pairs of elements at distance 2. For example, turned into produces 3 inversions. Combined this gives
Exercise 7.43
The next snippet is an expanded version of Program 7.2 from the book to also produce the inversion table .
Exercise 7.44
We can virtually follow the same combinatorial reasoning from the book (see the direct solution with CGFs) to derive the recurrence. The base cases are and for or . Otherwise,
Exercise 7.45 🌟
From Table 7.5 in the book, the EGF for involutions is
Every inversion in an involution can be uniquely classified as either an internal inversion (where and belong to the same 2-cycle) or a cross-inversion (where and belong to different cycles). Since expectation is linear, we can calculate the toll (see below) of each cycle configuration independently and sum them.
To find the CGF , we use the framework of additive parameters over sets: we isolate the specific cycle components that interact to create inversions, specify a toll function , multiply by the standard EGF kernel component , and then multiply the result by . Notice that we work at the level of cycles and let the machinery of GFs handle the translation of costs in terms of element wise inversions. We all the time operate at the same abstraction level, where cycles are the basic ingredients.
Internal Inversions (1 cycle of size 2)
Every 2-cycle creates exactly 1 internal inversion. Therefore, .
Cross-Inversions (One 1-cycle, One 2-cycle)
Suppose an inversion is formed by interactions between a 1-cycle and a 2-cycle. Suppose we have 3 elements (1, 2, 3). Cycles (1, 3)(2) yield the permutation 3, 2, 1. There are 2 cross-inversions. 1 is inverted relative to 2 and 2 is inverted relative to 3. Therefore, .
Cross-Inversions (Two 2-cycles)
Suppose we have 4 elements (1, 2, 3, 4). We know each 2-cycle inherently contains exactly 1 internal inversion. Therefore, any configuration of two 2-cycles will always have exactly 2 internal inversions. We can find the cross-inversions by looking at the total inversions of the sub-permutations:
Cycles (1, 4)(2, 3) yield the permutation 4, 3, 2, 1. This has 4 cross-inversions. Elements 2 and 3 are inverted relative to 4, and 1 is inverted relative to 2 and 3. Again, we don't care about total number of inversions; we’re counting purely inversions crossing the borders.
Cycles (1, 3)(2, 4) yields the permutation 3, 4, 1, 2. This has 2 cross-inversions. 1 is inverted relative to 4 and 2 is inverted relative to 3. These are the only pairs crossing the borders.
Therefore, .
Total Cost and Average
By the fundamental rules of additive parameters over sets, the total CGF is simply the sum of all the isolated toll-generating components, multiplied by the counting function . This gives
The average number of inversions in an involution is
The last line follows from the known ratio for the number of involutions
Exercise 7.46 🌟
We proceed to prove by induction on that is a fixed polynomial in for any fixed , when . Definitely this covers the phrase "for sufficiently large ."
The base case is satisfied, since only the identity permutation has no inversions, so for all . This is a fixed polynomial.
For the inductive step, assume that is a fixed polynomial in for all fixed , when . We use the standard "largest" construction for inversion numbers. Placing in a position that creates new inversions () and adding the inversions of the smaller permutation gives (see also Exercise 7.44)
Observe that the sum cannot have more than summands. Let’s pull out the first term and "move" it to the LHS
is fixed and by the inductive hypothesis all subordinate items are fixed polynomials on the RHS, hence the whole sum is also a fixed polynomial. By the standard properties of the finite difference operator (see the remark below), we can conclude that is a fixed polynomial in for any fixed when is large enough.
Exercise 7.47
Observe that the identity permutation, regard it as a sorted sequence of numbers from 1 to , has 0 inversions. It’s lattice path is exactly that "down-right-down-right..." diagonal. Any departure from this ideal line, either going above or below, means that some larger numbers were skipped during the traversal. Thus, cells between the actual path and the main diagonal denote inversions.
Exercise 7.48 🌟
To prove this combinatorially, we just need to verify two things: that paths can be concatenated perfectly, and that the inversions add up cleanly without any "cross-contamination."
The Consequence of a Diagonal Touch
What does it actually mean when a lattice path touches the main diagonal at some point ? If the path hits , it means we have taken exactly Right steps and Down steps. Consequently, the first values (the numbers ) have perfectly filled exactly Odd indices and Even indices. Because we process values in strictly increasing order, the path after will purely consist of the values .
The Additivity of Inversions
Can an element placed after the diagonal touch form an inversion with an element placed before the diagonal touch? The answer is no! Therefore, no "cross-contamination" may occur. All values placed after the touch are strictly larger than all values placed before the touch.
Therefore, if a path splits at the diagonal into Path and Path , the total number of inversions is strictly additive
Furthermore, because the values are perfectly partitioned into these blocks, there are no binomial choices to make about relabeling paths. This means we are strictly in the realm of OGFs. The paths concatenate directly like blocks. This additive nature of the problem permits clean decomposition into subproblems (reminiscent of the divide-and-conquer paradigm); recall the difficulties in analyzing tree height, where this wasn’t possible.
Proving the First Equation
Let be the class of all 2-ordered permutation lattice paths. Let be the analogous class for paths that never touch the diagonal except at the endpoints. Every single lattice path that returns to the diagonal can be uniquely decomposed into a sequence of these basic paths, just by chopping it at every single diagonal touch. This gives
Proving the Second Equation
The exact same logic applies to the second equation, just restricted to a subset of the space. Thus,
Exercise 7.49 🌟
The two equations in this exercise are direct translations of the physical geometry of the lattice paths (see also the previous two exercises).
The Elevation Principle
We can build path of length from path of length by
Notice that only touches the diagonal at the endpoints. Geometrically, this envelope (Right...Down) shifts the entire inner path up and right by one grid unit. The initial move adds 1 inversion together with the extra inversions due to moving away from the main diagonal.
Recall the definition of the BGF: the exponent of designates the number of inversions, whilst reflects the size. To encode the increase +1 in inversions over the whole length of the current path , we simply embellish the GF by passing instead of into In the same manner, the first Right move increases both the number of inversions and size by one, hence we just multiply the GF by . Therefore, .
The Asymmetry Principle
A path may be above or below the diagonal except at the endpoints. A path is restricted to always stay above the diagonal except at the endpoints. Let path represent the mirrored path around the diagonal (stays always below it except at the endpoints), where all Right moves were replaced by Down moves, and vice versa. Clearly, . Just by looking at Figure 7.10, we see that the number of inversions in and are generally different.
The path of the identity permutation starts with a Down move. Thus, the mirrored path is more aligned with this reference path than , since it also starts with a Down move. The initial difference of -1 is maintained throughout the whole length of . Therefore, has more inversions than . This gives
Therefore,
Exercise 7.50
Exercise 7.51
Let . We know our base functions are:
, since path reflects the lattice path of a binary tree. This provides the identity .
.
To save space, let write for and for .
We can also find by differentiating with respect to .
Now we just evaluate the three terms in that bracket using and our derivatives from step 1. The goal is to express everything on the RHS in terms of . It helps to remember that . We’ve
The biggest simplification happens in
Plugging everything back into the formula for and further simplifying, we get
Exercise 7.52
A 3-ordered permutation of total length consists of exactly 3 perfectly sorted sublists, each of length , interleaved together. Because the individual sublists are already sorted, inversions can only occur between elements of two different sublists. There are 3 pairs of such sublists.
Let be a random variable for the number of inversions between 2 ordered sublists. We already know the expectation of this variable from Theorem 7.9. By the linearity of expectation, we have
Wikipedia has a detailed coverage of shellsort including answers related to this exercise.
Exercise 7.53
Let be the average number of comparisons to sort an array of size using this hybrid method. The divide-and-conquer recurrence is (see also Theorem 7.9 from the book)
According to Theorem 2.5 from the book, the performance is commensurate with the driving function (see Exercise 2.68 for the value of ). We know that the quicksort implementation from Chapter 1 takes about comparisons. The objective is to find the threshold value below which the hybrid algorithm is faster. This gives
This is significantly larger than the one from Exercise 1.19. At any rate, the exact threshold isn’t that important. The key takeaway is that specialized sorting algorithms may play an important optimization role despite being asymptotically inferior compared to mainstream algorithms.
Exercise 7.54
The recurrence directly follows from Theorem 7.10 in the book and Exercise 3.71
with the boundary conditions:
,
for ,
for .
Exercise 7.55
The counting GF is . Let’s employ the double counting technique (see Exercise 2.34). The first way is
By Theorem 7.10, we also know that
Taking derivates of both sides gives
Recall that and the RHS evaluated at is simply . Equating both ways of computing gives
Exercise 7.56
Assume for convenience that is even and that the array is a random permutation of elements. Let be the index of the smallest number and be the index of the second smallest number. Initialize these indices based on the relative order of and . The algorithm proceeds as follows:
The loop variable points to the current pair of elements. It increases in increments of 2.
If then
If then
If then
Set
Else
Set
Set
Else If then
Set
Else perform the above checks just with and swapped.
The above algorithm performs exactly comparisons in every single case.
The index variable is set times, the average number of left-to-right minima in a permutation. The index variable is always updated whenever is altered, plus anytime a candidate for the second smallest appears. In a random permutation, the probability that the th element is the minimum of the first elements is . The book explains the reason. But the probability that it’s exactly the second smallest of the first elements is also using the same argumentation. Therefore, the total number of updates to index variables is .
Exercise 7.57
Assume that an “exchange” costs twice as much as a “record access.” We need to find the threshold value for which selection sort is a better choice than insertion sort. The model is based on statements about these sorting methods from the book
Exercise 7.58
We need to find the threshold value for which selection sort is a better choice than quicksort. The model is based on statements about these sorting methods from the book
Exercise 7.59
The asymptotic behavior is identical to the standard array version given in Theorem 7.11 from the book. Without swaps, the remaining sequence is intrinsically uniformly random, although not independent from the starting permutation. Therefore, computing the average still works via linearity of expectation, but finding the variance requires advanced methods.
To understand where dependence comes from, take a look at all permutations of elements and count the number of index updates for each of them (in both passes). The marginal probability that the second pass requires 1 update is 1/2. Nonetheless, if we know that we had 2 index updates in the first pass (these are associated with permutations (2, 1, 3), (3, 1, 2) and (2, 3, 1)) then .
Exercise 7.60
Let be the total volume of input data. Since there are records, and each record has words, the total input data is .
Notice that just reading the input requires time. Interestingly, selection sort turns out to have an optimal performance, since its number of compares and total data movement cost are both . Recall that only the first word is used as a key. All in all, it definitely has a total of runtime.
Observe also that no other enlisted sorting method achieves this goal, as their data movement costs are higher than linear in terms of input size.
Exercise 7.61
Similarly as in Theorem 7.13 from the book, we want to get
Let’s first extract the component depending on , whilst treating the rest as "constant." This gives
Substitute this back into our initial formula, and our extraction problem becomes
The Taylor series for is
The division by means that we must take a partial sum of this expansion upto . For a fixed and , as this is equivalent to
If we plug this asymptotic limit back into the expression from the beginning, we get
Exercise 7.62
The question, translated into the language of cycles in a permutation of length 100, is "What is the probability that a random permutation of length 100 contains no cycles of length strictly greater than 50?"
If , it is physically impossible to have more than one cycle of length when . Theorem 7.13 in the book already provides the average number of such cycles; here, it’s the same as the probability of having a cycle of that length. Since the events are mutually exclusive, the total probability of having any cycle larger than 50 is just the sum of the individual probabilities. Taking the complementary event, we get
Exercise 7.63
Let be the number of executions of the instruction k=p[k], where denotes a random permutation of length .
Let be the PGF for on permutations of size . Obviously, . We can decompose a random permutation based on the position of its leader (following Knuth's paper cited in the book related to this exercise). The first cycle always starts at index 1, so one leader is predefined. It helps to look at Figure 7.1 (and Foata's correspondence) to recognize leaders of cycles. Let’s focus on this particular leader, to understand the decomposition.
Because 1 is guaranteed to be the minimum of its cycle, the inner loop will fully traverse its cycle of length . Consequently, the target instruction runs times. For all the other members of the same cycle, the loop will abort earlier, effectively simulating the algorithm on the remaining elements. They physically split into two independent permutations (the rest of the cycle) and (the elements outside the cycle): one of size and one of size , respectively. Because the other leaders are equally likely to be anywhere, this yields the recursive relationship (see also Exercise 7.59)
Translating this into generating functions, we get the recurrence
Multiplying both sides by and sum over all gives
This factors perfectly into our target functional equation
Computing the mean and variance proceeds similarly to the steps laid out in Exercise 3.67 and will not be repeated here. The mean and variance are:
Exercise 7.64
The inner loop of Program 7.6 scans the array from left-to-right and bubbles up the current maximum in the corresponding subarray to its final position. This shifts the entries in the inversion sequence one position to the left and decreases their values by one.
If the next scan is done in the opposite direction, the current minimum is bubbled to its final position at the front. Because this displaces elements to the right, it shifts their entries in the inversion sequence one position to the right. However, because the sweeping element is smaller than the displaced elements, their inversion values stay the same (they do not increase), while the minimum element's inversion count drops to zero.
Exercise 7.65
The formula for extracting coefficients is based on a similar approach as for the longest cycle calculation from the book (see also Theorem 7.2)
where denotes a random variable for the length of the shortest cycle in a random permutation of elements. The Python script below "implements" this formula.
It outputs
If you multiply each entry by , then you get back the OEIS sequence A028417.
Last updated