**b: We say that f .n/ is asymptotically smaller than g.n/ if f .n/ D o.g.n//,andf .n/ is asymptotically larger than g.n/ if f .n/ D !.g.n//. One property of real numbers, however, does not carry over to asymptotic nota- tion: Trichotomy: For any two real numbers a and b, exactly one of the following must hold: a**

**b. Although any two real numbers can be compared, not all functions are asymptot- ically comparable. That is, for two functions f .n/ and g.n/, it may be the case that neither f .n/ D O.g.n// nor f .n/ D .g.n// holds. For example, we cannot compare the functions n and n1Csinn using asymptotic notation, since the value of the exponent in n1Csinn oscillates between 0 and 2, taking on all values in between. Exercises 3.1-1 Let f .n/ and g.n/ be asymptotically nonnegative functions. Using the basic deﬁ- nition of ‚-notation, prove that max.f .n/; g.n// D ‚.f .n/ C g.n//. 3.1-2 Show that for any real constants a and b,whereb>0, .n C a/b D ‚.nb/: (3.2)3.2 Standard notations and common functions 53 3.1-3 Explain why the statement, “The running time of algorithm A is at least O.n2/,” is meaningless. 3.1-4 Is 2nC1 D O.2n/?Is22n D O.2n/? 3.1-5 Prove Theorem 3.1. 3.1-6 Prove that the running time of an algorithm is ‚.g.n// if and only if its worst-case running time is O.g.n// and its best-case running time is .g.n//. 3.1-7 Prove that o.g.n// \ !.g.n// is the empty set. 3.1-8 We can extend our notation to the case of two parameters n and m that can go to inﬁnity independently at different rates. For a given function g.n;m/, we denote by O.g.n;m// the set of functions O.g.n;m// Dff.n;m/W there exist positive constants c, n0,andm0 such that 0 f.n;m/ cg.n; m/ for all n n0 or m m0g : Give corresponding deﬁnitions for .g.n; m// and ‚.g.n; m//. 3.2 Standard notations and common functions This section reviews some standard mathematical functions and notations and ex- plores the relationships among them. It also illustrates the use of the asymptotic notations. Monotonicity A function f .n/ is monotonically increasing if m n implies f.m/ f .n/. Similarly, it is monotonically decreasing if m n implies f.m/ f .n/.A function f .n/ is strictly increasing if m** f .n/.54 Chapter 3 Growth of Functions Floors and ceilings For any real number x, we denote the greatest integer less than or equal to x by bxc (read “the ﬂoor of x”) and the least integer greater than or equal to x by dxe (read “the ceiling of x”). For all real x, x 1 0, dx=ae b D l x ab m ; (3.4) bx=ac b D j x ab k ; (3.5) la b m a C .b 1/ b ; (3.6) ja b k a .b 1/ b : (3.7) The ﬂoor function f.x/D bxc is monotonically increasing, as is the ceiling func- tion f.x/D dxe. Modular arithmetic For any integer a and any positive integer n,thevaluea mod n is the remainder (or residue) of the quotient a=n: a mod n D a n ba=nc : (3.8) It follows that 0 a mod n0.Foran asymptotically positive polynomial p.n/ of degree d,wehavep.n/ D ‚.nd /.For any real constant a 0, the function na is monotonically increasing, and for any real constant a 0, the function na is monotonically decreasing. We say that a function f .n/ is polynomially bounded if f .n/ D O.nk/ for some constant k. Exponentials For all real a>0, m,andn, we have the following identities: a0 D 1; a1 D a; a1 D 1=a ; .am/n D amn ; .am/n D .an/m ; aman D amCn : For all n and a 1, the function an is monotonically increasing in n.When convenient, we shall assume 00 D 1. We can relate the rates of growth of polynomials and exponentials by the fol- lowing fact. For all real constants a and b such that a>1, limn!1 nb an D 0; (3.10) from which we can conclude that nb D o.an/: Thus, any exponential function with a base strictly greater than 1 grows faster than any polynomial function. Using e to denote 2:71828 : : :, the base of the natural logarithm function, we have for all real x, ex D 1 C x C x2 2Š C x3 3Š C D 1X iD0 xi iŠ ; (3.11)56 Chapter 3 Growth of Functions where “Š” denotes the factorial function deﬁned later in this section. For all real x, we have the inequality ex 1 C x; (3.12) where equality holds only when x D 0.Whenjxj 1, we have the approximation 1 C x ex 1 C x C x2 : (3.13) When x ! 0, the approximation of ex by 1 C x is quite good: ex D 1 C x C ‚.x2/: (In this equation, the asymptotic notation is used to describe the limiting behavior as x ! 0 rather than as x !1.) We have for all x, limn!1 1 C x n n D ex : (3.14) Logarithms We shall use the following notations: lg n D log2 n (binary logarithm) , ln n D loge n (natural logarithm) , lgk n D .lg n/k (exponentiation) , lg lg n D lg.lg n/ (composition) . An important notational convention we shall adopt is that logarithm functions will apply only to the next term in the formula,sothatlgn C k will mean .lg n/ C k and not lg.n C k/. If we hold b>1constant, then for n>0, the function logb n is strictly increasing. For all real a>0, b>0, c>0,andn, a D blogb a ; logc.ab/ D logc a C logc b; logb an D n logb a; logb a D logc a logc b ; (3.15) logb.1=a/ Dlogb a; logb a D 1 loga b ; alogb c D clogb a ; (3.16) where, in each equation above, logarithm bases are not 1.3.2 Standard notations and common functions 57 By equation (3.15), changing the base of a logarithm from one constant to an- other changes the value of the logarithm by only a constant factor, and so we shall often use the notation “lg n” when we don’t care about constant factors, such as in O-notation. Computer scientists ﬁnd 2 to be the most natural base for logarithms because so many algorithms and data structures involve splitting a problem into two parts. There is a simple series expansion for ln.1 C x/ when jxj <1: ln.1 C x/ D x x2 2 C x3 3 x4 4 C x5 5 : We also have the following inequalities for x>1: x 1 C x ln.1 C x/ x; (3.17) where equality holds only for x D 0. We say that a function f .n/ is polylogarithmically bounded if f .n/ D O.lgk n/ for some constant k. We can relate the growth of polynomials and polylogarithms by substituting lg n for n and 2a for a in equation (3.10), yielding limn!1 lgb n .2a/lg n D limn!1 lgb n na D 0: From this limit, we can conclude that lgb n D o.na/ for any constant a>0. Thus, any positive polynomial function grows faster than any polylogarithmic function. Factorials The notation nŠ (read “n factorial”) is deﬁned for integers n 0 as nŠ D ( 1 if n D 0; n .n 1/Š if n>0: Thus, nŠ D 1 2 3 n. A weak upper bound on the factorial function is nŠ nn, since each of the n terms in the factorial product is at most n. Stirling’s approximation, nŠ D p 2n n e n 1 C ‚ 1 n ; (3.18)58 Chapter 3 Growth of Functions where e is the base of the natural logarithm, gives us a tighter upper bound, and a lower bound as well. As Exercise 3.2-3 asks you to prove, nŠ D o.nn/; nŠ D !.2n/; lg.nŠ/ D ‚.n lg n/ ; (3.19) where Stirling’s approximation is helpful in proving equation (3.19). The following equation also holds for all n 1: nŠ D p 2n n e n e˛n (3.20) where 1 12n C 1 <˛n < 1 12n : (3.21) Functional iteration We use the notation f .i/.n/ to denote the function f .n/ iteratively applied i times to an initial value of n. Formally, let f .n/ be a function over the reals. For non- negative integers i, we recursively deﬁne f .i/.n/ D ( n if i D 0; f.f.i1/.n// if i>0: For example, if f .n/ D 2n,thenf .i/.n/ D 2i n. The iterated logarithm function We use the notation lg n (read “log star of n”) to denote the iterated logarithm, de- ﬁned as follows. Let lg.i/ n be as deﬁned above, with f .n/ D lg n. Because the log- arithm of a nonpositive number is undeﬁned, lg.i/ n is deﬁned only if lg.i1/ n>0. Be sure to distinguish lg.i/ n (the logarithm function applied i times in succession, starting with argument n) from lgi n (the logarithm of n raised to the ith power). Then we deﬁne the iterated logarithm function as lg n D min ˚ i 0 W lg.i/ n 1 : The iterated logarithm is a very slowly growing function: lg 2 D 1; lg 4 D 2; lg 16 D 3; lg 65536 D 4; lg.265536/ D 5:3.2 Standard notations and common functions 59 Since the number of atoms in the observable universe is estimated to be about 1080, which is much less than 265536, we rarely encounter an input size n such that lg n>5. Fibonacci numbers We deﬁne the Fibonacci numbers by the following recurrence: F0 D 0; F1 D 1; (3.22) Fi D Fi1 C Fi2 for i 2: Thus, each Fibonacci number is the sum of the two previous ones, yielding the sequence 0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; : : : : Fibonacci numbers are related to the golden ratio and to its conjugate y,which are the two roots of the equation x2 D x C 1 (3.23) and are given by the following formulas (see Exercise 3.2-6): D 1 C p 5 2 (3.24) D 1:61803 : : : ; y D 1 p 5 2 D:61803 : : : : Speciﬁcally, we have Fi D i yi p 5 ; which we can prove by induction (Exercise 3.2-7). Since ˇˇy ˇˇ <1,wehave ˇˇyi ˇˇ p 5 < 1p 5 < 1 2 ; which implies that60 Chapter 3 Growth of Functions Fi D i p 5 C 1 2 ; (3.25) which is to say that the ith Fibonacci number Fi is equal to i = p 5 rounded to the nearest integer. Thus, Fibonacci numbers grow exponentially. Exercises 3.2-1 Show that if f .n/ and g.n/ are monotonically increasing functions, then so are the functions f .n/ C g.n/ and f .g.n//,andiff .n/ and g.n/ are in addition nonnegative, then f .n/ g.n/ is monotonically increasing. 3.2-2 Prove equation (3.16). 3.2-3 Prove equation (3.19). Also prove that nŠ D !.2n/ and nŠ D o.nn/. 3.2-4 ? Is the function dlg neŠ polynomially bounded? Is the function dlg lg neŠ polynomi- ally bounded? 3.2-5 ? Which is asymptotically larger: lg.lg n/ or lg.lg n/? 3.2-6 Show that the golden ratio and its conjugate y both satisfy the equation x2 D x C 1. 3.2-7 Prove by induction that the ith Fibonacci number satisﬁes the equality Fi D i yi p 5 ; where is the golden ratio and y is its conjugate. 3.2-8 Show that k ln k D ‚.n/ implies k D ‚.n= ln n/.Problems for Chapter 3 61 Problems 3-1 Asymptotic behavior of polynomials Let p.n/ D dX iD0 ai ni ; where ad >0,beadegree-d polynomial in n,andletk be a constant. Use the deﬁnitions of the asymptotic notations to prove the following properties. a. If k d,thenp.n/ D O.nk/. b. If k d,thenp.n/ D .nk/. c. If k D d,thenp.n/ D ‚.nk/. d. If k>d,thenp.n/ D o.nk/. e. If k0,andc>1are constants. Your answer should be in the form of the table with “yes” or “no” written in each box. ABO o ! ‚ a. lgk nn b. nk cn c. pnnsinn d. 2n 2n=2 e. nlg c clg n f. lg.nŠ/ lg.nn/ 3-3 Ordering by asymptotic growth rates a. Rank the following functions by order of growth; that is, ﬁnd an arrangement g1;g2;:::;g30 of the functions satisfying g1 D .g2/, g2 D .g3/, ..., g29 D .g30/. Partition your list into equivalence classes such that functions f .n/ and g.n/ are in the same class if and only if f .n/ D ‚.g.n//.62 Chapter 3 Growth of Functions lg.lg n/ 2lg n . p 2/lg n n2 nŠ .lg n/Š . 3 2 /n n3 lg2 n lg.nŠ/ 22n n1= lg n ln ln n lg nn 2n nlg lg n ln n1 2lg n .lg n/lg n en 4lg n .n C 1/Š p lg n lg.lg n/ 2 p2 lg n n2n n lg n22nC1 b. Give an example of a single nonnegative function f .n/ such that for all func- tions gi .n/ in part (a), f .n/ is neither O.gi .n// nor .gi .n//. 3-4 Asymptotic notation properties Let f .n/ and g.n/ be asymptotically positive functions. Prove or disprove each of the following conjectures. a. f .n/ D O.g.n// implies g.n/ D O.f .n//. b. f .n/ C g.n/ D ‚.min.f .n/; g.n///. c. f .n/ D O.g.n// implies lg.f .n// D O.lg.g.n///, where lg.g.n// 1 and f .n/ 1 for all sufﬁciently large n. d. f .n/ D O.g.n// implies 2f.n/ D O 2g.n/ . e. f .n/ D O ..f .n//2/. f. f .n/ D O.g.n// implies g.n/ D .f .n//. g. f .n/ D ‚.f .n=2//. h. f .n/ C o.f .n// D ‚.f .n//. 3-5 Variations on O and ˝ Some authors deﬁne in a slightly different way than we do; let’s use 1 (read “omega inﬁnity”) for this alternative deﬁnition. We say that f .n/ D 1 .g.n// if there exists a positive constant c such that f .n/ cg.n/ 0 for inﬁnitely many integers n. a. Show that for any two functions f .n/ and g.n/ that are asymptotically nonneg- ative, either f .n/ D O.g.n// or f .n/ D 1 .g.n// or both, whereas this is not true if we use in place of 1 .Problems for Chapter 3 63 b. Describe the potential advantages and disadvantages of using 1 instead of to characterize the running times of programs. Some authors also deﬁne O in a slightly different manner; let’s use O0 for the alternative deﬁnition. We say that f .n/ D O0.g.n// if and only if jf .n/j D O.g.n//. c. What happens to each direction of the “if and only if” in Theorem 3.1 if we substitute O0 for O but still use ? Some authors deﬁne eO (read “soft-oh”) to mean O with logarithmic factors ig- nored: eO.g.n// Dff .n/ W there exist positive constants c, k,andn0 such that 0 f .n/ cg.n/ lgk.n/ for all n n0g : d. Deﬁne e and e‚ in a similar manner. Prove the corresponding analog to Theo- rem 3.1. 3-6 Iterated functions We can apply the iteration operator used in the lg function to any monotonically increasing function f .n/ over the reals. For a given constant c 2 R,wedeﬁnethe iterated function f c by f c .n/ D min ˚ i 0 W f .i/.n/ c ; which need not be well deﬁned in all cases. In other words, the quantity f c .n/ is the number of iterated applications of the function f required to reduce its argu- ment down to c or less. For each of the following functions f .n/ and constants c, give as tight a bound as possible on f c .n/. f .n/ c f c .n/ a. n 10 b. lg n1 c. n=2 1 d. n=2 2 e. pn2 f. pn1 g. n1=3 2 h. n= lg n264 Chapter 3 Growth of Functions Chapter notes Knuth [209] traces the origin of the O-notation to a number-theory text by P. Bach- mann in 1892. The o-notation was invented by E. Landau in 1909 for his discussion of the distribution of prime numbers. The and ‚ notations were advocated by Knuth [213] to correct the popular, but technically sloppy, practice in the literature of using O-notation for both upper and lower bounds. Many people continue to use the O-notation where the ‚-notation is more technically precise. Further dis- cussion of the history and development of asymptotic notations appears in works by Knuth [209, 213] and Brassard and Bratley [54]. Not all authors deﬁne the asymptotic notations in the same way, although the various deﬁnitions agree in most common situations. Some of the alternative def- initions encompass functions that are not asymptotically nonnegative, as long as their absolute values are appropriately bounded. Equation (3.20) is due to Robbins [297]. Other properties of elementary math- ematical functions can be found in any good mathematical reference, such as Abramowitz and Stegun [1] or Zwillinger [362], or in a calculus book, such as Apostol [18] or Thomas et al. [334]. Knuth [209] and Graham, Knuth, and Patash- nik [152] contain a wealth of material on discrete mathematics as used in computer science.4 Divide-and-Conquer In Section 2.3.1, we saw how merge sort serves as an example of the divide-and- conquer paradigm. Recall that in divide-and-conquer, we solve a problem recur- sively, applying three steps at each level of the recursion: Divide the problem into a number of subproblems that are smaller instances of the same problem. Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner. Combine the solutions to the subproblems into the solution for the original prob- lem. When the subproblems are large enough to solve recursively, we call that the recur- sive case. Once the subproblems become small enough that we no longer recurse, we say that the recursion “bottoms out” and that we have gotten down to the base case. Sometimes, in addition to subproblems that are smaller instances of the same problem, we have to solve subproblems that are not quite the same as the original problem. We consider solving such subproblems as part of the combine step. In this chapter, we shall see more algorithms based on divide-and-conquer. The ﬁrst one solves the maximum-subarray problem: it takes as input an array of num- bers, and it determines the contiguous subarray whose values have the greatest sum. Then we shall see two divide-and-conquer algorithms for multiplying n n matri- ces. One runs in ‚.n3/ time, which is no better than the straightforward method of multiplying square matrices. But the other, Strassen’s algorithm, runs in O.n2:81/ time, which beats the straightforward method asymptotically. Recurrences Recurrences go hand in hand with the divide-and-conquer paradigm, because they give us a natural way to characterize the running times of divide-and-conquer algo- rithms. A recurrence is an equation or inequality that describes a function in terms66 Chapter 4 Divide-and-Conquer of its value on smaller inputs. For example, in Section 2.3.2 we described the worst-case running time T .n/ of the MERGE-SORT procedure by the recurrence T .n/ D ( ‚.1/ if n D 1; 2T .n=2/ C ‚.n/ if n>1; (4.1) whose solution we claimed to be T .n/ D ‚.n lg n/. Recurrences can take many forms. For example, a recursive algorithm might divide subproblems into unequal sizes, such as a 2=3-to-1=3 split. If the divide and combine steps take linear time, such an algorithm would give rise to the recurrence T .n/ D T .2n=3/ C T .n=3/ C ‚.n/. Subproblems are not necessarily constrained to being a constant fraction of the original problem size. For example, a recursive version of linear search (see Exercise 2.1-3) would create just one subproblem containing only one el- ement fewer than the original problem. Each recursive call would take con- stant time plus the time for the recursive calls it makes, yielding the recurrence T .n/ D T.n 1/ C ‚.1/. This chapter offers three methods for solving recurrences—that is, for obtaining asymptotic “‚”or“O” bounds on the solution: In the substitution method, we guess a bound and then use mathematical in- duction to prove our guess correct. The recursion-tree method converts the recurrence into a tree whose nodes represent the costs incurred at various levels of the recursion. We use techniques for bounding summations to solve the recurrence. The master method provides bounds for recurrences of the form T .n/ D aT .n=b/ C f .n/ ; (4.2) where a 1, b>1,andf .n/ is a given function. Such recurrences arise frequently. A recurrence of the form in equation (4.2) characterizes a divide- and-conquer algorithm that creates a subproblems, each of which is 1=b the size of the original problem, and in which the divide and combine steps together take f .n/ time. To use the master method, you will need to memorize three cases, but once you do that, you will easily be able to determine asymptotic bounds for many simple recurrences. We will use the master method to determine the running times of the divide-and-conquer algorithms for the maximum-subarray problem and for matrix multiplication, as well as for other algorithms based on divide- and-conquer elsewhere in this book.Chapter 4 Divide-and-Conquer 67 Occasionally, we shall see recurrences that are not equalities but rather inequal- ities, such as T .n/ 2T .n=2/ C ‚.n/. Because such a recurrence states only an upper bound on T .n/, we will couch its solution using O-notation rather than ‚-notation. Similarly, if the inequality were reversed to T .n/ 2T .n=2/ C ‚.n/, then because the recurrence gives only a lower bound on T .n/, we would use -notation in its solution. Technicalities in recurrences In practice, we neglect certain technical details when we state and solve recur- rences. For example, if we call MERGE-SORT on n elements when n is odd, we end up with subproblems of size bn=2c and dn=2e. Neither size is actually n=2, because n=2 is not an integer when n is odd. Technically, the recurrence describing the worst-case running time of MERGE-SORT is really T .n/ D ( ‚.1/ if n D 1; T.dn=2e/ C T.bn=2c/ C ‚.n/ if n>1: (4.3) Boundary conditions represent another class of details that we typically ignore. Since the running time of an algorithm on a constant-sized input is a constant, the recurrences that arise from the running times of algorithms generally have T .n/ D ‚.1/ for sufﬁciently small n. Consequently, for convenience, we shall generally omit statements of the boundary conditions of recurrences and assume that T .n/ is constant for small n. For example, we normally state recurrence (4.1) as T .n/ D 2T .n=2/ C ‚.n/ ; (4.4) without explicitly giving values for small n. The reason is that although changing the value of T.1/ changes the exact solution to the recurrence, the solution typi- cally doesn’t change by more than a constant factor, and so the order of growth is unchanged. When we state and solve recurrences, we often omit ﬂoors, ceilings, and bound- ary conditions. We forge ahead without these details and later determine whether or not they matter. They usually do not, but you should know when they do. Ex- perience helps, and so do some theorems stating that these details do not affect the asymptotic bounds of many recurrences characterizing divide-and-conquer algo- rithms (see Theorem 4.1). In this chapter, however, we shall address some of these details and illustrate the ﬁne points of recurrence solution methods.68 Chapter 4 Divide-and-Conquer 4.1 The maximum-subarray problem Suppose that you been offered the opportunity to invest in the Volatile Chemical Corporation. Like the chemicals the company produces, the stock price of the Volatile Chemical Corporation is rather volatile. You are allowed to buy one unit of stock only one time and then sell it at a later date, buying and selling after the close of trading for the day. To compensate for this restriction, you are allowed to learn what the price of the stock will be in the future. Your goal is to maximize your proﬁt. Figure 4.1 shows the price of the stock over a 17-day period. You may buy the stock at any one time, starting after day 0, when the price is $100 per share. Of course, you would want to “buy low, sell high”—buy at the lowest possible price and later on sell at the highest possible price—to maximize your proﬁt. Unfortunately, you might not be able to buy at the lowest price and then sell at the highest price within a given period. In Figure 4.1, the lowest price occurs after day 7, which occurs after the highest price, after day 1. You might think that you can always maximize proﬁt by either buying at the lowest price or selling at the highest price. For example, in Figure 4.1, we would maximize proﬁt by buying at the lowest price, after day 7. If this strategy always worked, then it would be easy to determine how to maximize proﬁt: ﬁnd the highest and lowest prices, and then work left from the highest price to ﬁnd the lowest prior price, work right from the lowest price to ﬁnd the highest later price, and take the pair with the greater difference. Figure 4.2 shows a simple counterexample, 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 120 110 100 90 80 70 60 Day 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Price 100 113 110 85 105 102 86 63 81 101 94 106 101 79 94 90 97 Change 13 3 25 20 3 16 23 18 20 7125 22 15 47 Figure 4.1 Information about the price of stock in the Volatile Chemical Corporation after the close of trading over a period of 17 days. The horizontal axis of the chart indicates the day, and the vertical axis shows the price. The bottom row of the table gives the change in price from the previous day.4.1 The maximum-subarray problem 69 01234 11 10 9 8 7 6 Day 01 23 4 Price 10 11 7 10 6 Change 1 434 Figure 4.2 An example showing that the maximum proﬁt does not always start at the lowest price or end at the highest price. Again, the horizontal axis indicates the day, and the vertical axis shows the price. Here, the maximum proﬁt of $3 per share would be earned by buying after day 2 and selling after day 3. The price of $7 after day 2 is not the lowest price overall, and the price of $10 after day 3 is not the highest price overall. demonstrating that the maximum proﬁt sometimes comes neither by buying at the lowest price nor by selling at the highest price. A brute-force solution We can easily devise a brute-force solution to this problem: just try every possible pair of buy and sell dates in which the buy date precedes the sell date. A period of n days has n 2 such pairs of dates. Since n 2 is ‚.n2/, and the best we can hope for is to evaluate each pair of dates in constant time, this approach would take .n2/ time. Can we do better? A transformation In order to design an algorithm with an o.n2/ running time, we will look at the input in a slightly different way. We want to ﬁnd a sequence of days over which the net change from the ﬁrst day to the last is maximum. Instead of looking at the daily prices, let us instead consider the daily change in price, where the change on day i is the difference between the prices after day i 1 and after day i. The table in Figure 4.1 shows these daily changes in the bottom row. If we treat this row as an array A, shown in Figure 4.3, we now want to ﬁnd the nonempty, contiguous subarray of A whose values have the largest sum. We call this contiguous subarray the maximum subarray. For example, in the array of Figure 4.3, the maximum subarray of AŒ1 : : 16 is AŒ8 : : 11, with the sum 43. Thus, you would want to buy the stock just before day 8 (that is, after day 7) and sell it after day 11, earning a proﬁt of $43 per share. At ﬁrst glance, this transformation does not help. We still need to checkn1 2 D ‚.n2/ subarrays for a period of n days. Exercise 4.1-2 asks you to show70 Chapter 4 Divide-and-Conquer 13 1 –3 2 –25 3 20 4 –3 5 –16 6 –23 7 8 9 10 maximum subarray 11 18 12 20 13 –7 14 12 15 7 16 –5 –22 15 –4A Figure 4.3 The change in stock prices as a maximum-subarray problem. Here, the subar- ray AŒ8 : : 11,withsum43, has the greatest sum of any contiguous subarray of array A. that although computing the cost of one subarray might take time proportional to the length of the subarray, when computing all ‚.n2/ subarray sums, we can orga- nize the computation so that each subarray sum takes O.1/ time, given the values of previously computed subarray sums, so that the brute-force solution takes ‚.n2/ time. So let us seek a more efﬁcient solution to the maximum-subarray problem. When doing so, we will usually speak of “a” maximum subarray rather than “the” maximum subarray, since there could be more than one subarray that achieves the maximum sum. The maximum-subarray problem is interesting only when the array contains some negative numbers. If all the array entries were nonnegative, then the maximum-subarray problem would present no challenge, since the entire array would give the greatest sum. A solution using divide-and-conquer Let’s think about how we might solve the maximum-subarray problem using the divide-and-conquer technique. Suppose we want to ﬁnd a maximum subar- ray of the subarray AŒlow ::high. Divide-and-conquer suggests that we divide the subarray into two subarrays of as equal size as possible. That is, we ﬁnd the midpoint, say mid, of the subarray, and consider the subarrays AŒlow ::mid and AŒmid C 1::high. As Figure 4.4(a) shows, any contiguous subarray AŒi : : j of AŒlow ::high must lie in exactly one of the following places: entirely in the subarray AŒlow ::mid,sothatlow i j mid, entirely in the subarray AŒmid C 1::high,sothatmid *left-sum 6 left-sum D sum 7 max-left D i 8 right-sum D1 9 sum D 0 10 for j D mid C 1 to high 11 sum D sum C AŒj 12 if sum > right-sum 13 right-sum D sum 14 max-right D j 15 return .max-left; max-right; left-sum C right-sum/72 Chapter 4 Divide-and-Conquer This procedure works as follows. Lines 1–7 ﬁnd a maximum subarray of the left half, AŒlow ::mid. Since this subarray must contain AŒmid,thefor loop of lines 3–7 starts the index i at mid and works down to low, so that every subarray it considers is of the form AŒi : : mid. Lines 1–2 initialize the variables left-sum, which holds the greatest sum found so far, and sum, holding the sum of the entries in AŒi : : mid. Whenever we ﬁnd, in line 5, a subarray AŒi : : mid with a sum of values greater than left-sum, we update left-sum to this subarray’s sum in line 6, and in line 7 we update the variable max-left to record this index i. Lines 8–14 work analogously for the right half, AŒmidC1::high. Here, the for loop of lines 10–14 starts the index j at midC1 and works up to high, so that every subarray it considers is of the form AŒmid C 1::j. Finally, line 15 returns the indices max-left and max-right that demarcate a maximum subarray crossing the midpoint, along with the sum left-sumCright-sum of the values in the subarray AŒmax-left ::max-right. If the subarray AŒlow ::high contains n entries (so that n D high low C 1), we claim that the call FIND-MAX-CROSSING-SUBARRAY.A; low; mid; high/ takes ‚.n/ time. Since each iteration of each of the two for loops takes ‚.1/ time, we just need to count up how many iterations there are altogether. The for loop of lines 3–7 makes mid low C 1 iterations, and the for loop of lines 10–14 makes high mid iterations, and so the total number of iterations is .mid low C 1/ C .high mid/ D high low C 1 D n: With a linear-time FIND-MAX-CROSSING-SUBARRAY procedure in hand, we can write pseudocode for a divide-and-conquer algorithm to solve the maximum- subarray problem: FIND-MAXIMUM-SUBARRAY.A; low; high/ 1 if high == low 2 return .low; high;AŒlow/ // base case: only one element 3 else mid D b.low C high/=2c 4 .left-low; left-high; left-sum/ D FIND-MAXIMUM-SUBARRAY.A; low; mid/ 5 .right-low; right-high; right-sum/ D FIND-MAXIMUM-SUBARRAY.A; mid C 1; high/ 6 .cross-low; cross-high; cross-sum/ D FIND-MAX-CROSSING-SUBARRAY.A; low; mid; high/ 7 if left-sum right-sum and left-sum cross-sum 8 return .left-low; left-high; left-sum/ 9 elseif right-sum left-sum and right-sum cross-sum 10 return .right-low; right-high; right-sum/ 11 else return .cross-low; cross-high; cross-sum/4.1 The maximum-subarray problem 73 The initial call FIND-MAXIMUM-SUBARRAY.A;1;A:length/ will ﬁnd a maxi- mum subarray of AŒ1 : : n. Similar to FIND-MAX-CROSSING-SUBARRAY, the recursive procedure FIND- MAXIMUM-SUBARRAY returns a tuple containing the indices that demarcate a maximum subarray, along with the sum of the values in a maximum subarray. Line 1 tests for the base case, where the subarray has just one element. A subar- ray with just one element has only one subarray—itself—and so line 2 returns a tuple with the starting and ending indices of just the one element, along with its value. Lines 3–11 handle the recursive case. Line 3 does the divide part, comput- ing the index mid of the midpoint. Let’s refer to the subarray AŒlow ::mid as the left subarray and to AŒmid C 1::high as the right subarray. Because we know that the subarray AŒlow ::high contains at least two elements, each of the left and right subarrays must have at least one element. Lines 4 and 5 conquer by recur- sively ﬁnding maximum subarrays within the left and right subarrays, respectively. Lines 6–11 form the combine part. Line 6 ﬁnds a maximum subarray that crosses the midpoint. (Recall that because line 6 solves a subproblem that is not a smaller instance of the original problem, we consider it to be in the combine part.) Line 7 tests whether the left subarray contains a subarray with the maximum sum, and line 8 returns that maximum subarray. Otherwise, line 9 tests whether the right subarray contains a subarray with the maximum sum, and line 10 returns that max- imum subarray. If neither the left nor right subarrays contain a subarray achieving the maximum sum, then a maximum subarray must cross the midpoint, and line 11 returns it. Analyzing the divide-and-conquer algorithm Next we set up a recurrence that describes the running time of the recursive FIND- MAXIMUM-SUBARRAY procedure. As we did when we analyzed merge sort in Section 2.3.2, we make the simplifying assumption that the original problem size isapowerof2, so that all subproblem sizes are integers. We denote by T .n/ the running time of FIND-MAXIMUM-SUBARRAY on a subarray of n elements. For starters, line 1 takes constant time. The base case, when n D 1, is easy: line 2 takes constant time, and so T.1/D ‚.1/ : (4.5) The recursive case occurs when n>1. Lines 1 and 3 take constant time. Each of the subproblems solved in lines 4 and 5 is on a subarray of n=2 elements (our assumption that the original problem size is a power of 2 ensures that n=2 is an integer), and so we spend T .n=2/ time solving each of them. Because we have to solve two subproblems—for the left subarray and for the right subarray—the contribution to the running time from lines 4 and 5 comes to 2T .n=2/.Aswehave74 Chapter 4 Divide-and-Conquer already seen, the call to FIND-MAX-CROSSING-SUBARRAY in line 6 takes ‚.n/ time. Lines 7–11 take only ‚.1/ time. For the recursive case, therefore, we have T .n/ D ‚.1/ C 2T .n=2/ C ‚.n/ C ‚.1/ D 2T .n=2/ C ‚.n/ : (4.6) Combining equations (4.5) and (4.6) gives us a recurrence for the running time T .n/ of FIND-MAXIMUM-SUBARRAY: T .n/ D ( ‚.1/ if n D 1; 2T .n=2/ C ‚.n/ if n>1: (4.7) This recurrence is the same as recurrence (4.1) for merge sort. As we shall see from the master method in Section 4.5, this recurrence has the solution T .n/ D ‚.n lg n/. You might also revisit the recursion tree in Figure 2.5 to un- derstand why the solution should be T .n/ D ‚.n lg n/. Thus, we see that the divide-and-conquer method yields an algorithm that is asymptotically faster than the brute-force method. With merge sort and now the maximum-subarray problem, we begin to get an idea of how powerful the divide- and-conquer method can be. Sometimes it will yield the asymptotically fastest algorithm for a problem, and other times we can do even better. As Exercise 4.1-5 shows, there is in fact a linear-time algorithm for the maximum-subarray problem, and it does not use divide-and-conquer. Exercises 4.1-1 What does FIND-MAXIMUM-SUBARRAY return when all elements of A are nega- tive? 4.1-2 Write pseudocode for the brute-force method of solving the maximum-subarray problem. Your procedure should run in ‚.n2/ time. 4.1-3 Implement both the brute-force and recursive algorithms for the maximum- subarray problem on your own computer. What problem size n0 gives the crossover point at which the recursive algorithm beats the brute-force algorithm? Then, change the base case of the recursive algorithm to use the brute-force algorithm whenever the problem size is less than n0. Does that change the crossover point? 4.1-4 Suppose we change the deﬁnition of the maximum-subarray problem to allow the result to be an empty subarray, where the sum of the values of an empty subar-4.2 Strassen’s algorithm for matrix multiplication 75 ray is 0. How would you change any of the algorithms that do not allow empty subarrays to permit an empty subarray to be the result? 4.1-5 Use the following ideas to develop a nonrecursive, linear-time algorithm for the maximum-subarray problem. Start at the left end of the array, and progress toward the right, keeping track of the maximum subarray seen so far. Knowing a maximum subarray of AŒ1 : : j , extend the answer to ﬁnd a maximum subarray ending at in- dex j C1 by using the following observation: a maximum subarray of AŒ1 : : j C 1 is either a maximum subarray of AŒ1 : : j or a subarray AŒi : : j C 1,forsome 1 i j C 1. Determine a maximum subarray of the form AŒi : : j C 1 in constant time based on knowing a maximum subarray ending at index j . 4.2 Strassen’s algorithm for matrix multiplication If you have seen matrices before, then you probably know how to multiply them. (Otherwise, you should read Section D.1 in Appendix D.) If A D .aij / and B D .bij / are square n n matrices, then in the product C D A B,wedeﬁnethe entry cij ,fori;j D 1;2;:::;n,by cij D nX kD1 aik bkj : (4.8) We must compute n2 matrix entries, and each is the sum of n values. The following procedure takes n n matrices A and B and multiplies them, returning their n n product C. We assume that each matrix has an attribute rows, giving the number of rows in the matrix. SQUARE-MATRIX-MULTIPLY.A; B/ 1 n D A:rows 2letC beanewn n matrix 3 for i D 1 to n 4 for j D 1 to n 5 cij D 0 6 for k D 1 to n 7 cij D cij C aik bkj 8 return C The SQUARE-MATRIX-MULTIPLY procedure works as follows. The for loop of lines 3–7 computes the entries of each row i, and within a given row i,the76 Chapter 4 Divide-and-Conquer for loop of lines 4–7 computes each of the entries cij , for each column j .Line5 initializes cij to 0 as we start computing the sum given in equation (4.8), and each iteration of the for loop of lines 6–7 adds in one more term of equation (4.8). Because each of the triply-nested for loops runs exactly n iterations, and each execution of line 7 takes constant time, the SQUARE-MATRIX-MULTIPLY proce- dure takes ‚.n3/ time. You might at ﬁrst think that any matrix multiplication algorithm must take .n3/ time, since the natural deﬁnition of matrix multiplication requires that many mul- tiplications. You would be incorrect, however: we have a way to multiply matrices in o.n3/ time. In this section, we shall see Strassen’s remarkable recursive algo- rithm for multiplying n n matrices. It runs in ‚.nlg 7/ time, which we shall show in Section 4.5. Since lg 7 lies between 2:80 and 2:81, Strassen’s algorithm runs in O.n2:81/ time, which is asymptotically better than the simple SQUARE-MATRIX- MULTIPLY procedure. A simple divide-and-conquer algorithm To keep things simple, when we use a divide-and-conquer algorithm to compute the matrix product C D A B, we assume that n is an exact power of 2 in each of the n n matrices. We make this assumption because in each divide step, we will divide n n matrices into four n=2 n=2 matrices, and by assuming that n is an exact power of 2, we are guaranteed that as long as n 2, the dimension n=2 is an integer. Suppose that we partition each of A, B,andC into four n=2 n=2 matrices A D A11 A12 A21 A22 ;BD B11 B12 B21 B22 ;CD C11 C12 C21 C22 ; (4.9) so that we rewrite the equation C D A B as C11 C12 C21 C22 D A11 A12 A21 A22 B11 B12 B21 B22 : (4.10) Equation (4.10) corresponds to the four equations C11 D A11 B11 C A12 B21 ; (4.11) C12 D A11 B12 C A12 B22 ; (4.12) C21 D A21 B11 C A22 B21 ; (4.13) C22 D A21 B12 C A22 B22 : (4.14) Each of these four equations speciﬁes two multiplications of n=2 n=2 matrices and the addition of their n=2 n=2 products. We can use these equations to create a straightforward, recursive, divide-and-conquer algorithm:4.2 Strassen’s algorithm for matrix multiplication 77 SQUARE-MATRIX-MULTIPLY-RECURSIVE.A; B/ 1 n D A:rows 2letC be a new n n matrix 3 if n == 1 4 c11 D a11 b11 5 else partition A, B,andC as in equations (4.9) 6 C11 D SQUARE-MATRIX-MULTIPLY-RECURSIVE.A11;B11/ C SQUARE-MATRIX-MULTIPLY-RECURSIVE.A12;B21/ 7 C12 D SQUARE-MATRIX-MULTIPLY-RECURSIVE.A11;B12/ C SQUARE-MATRIX-MULTIPLY-RECURSIVE.A12;B22/ 8 C21 D SQUARE-MATRIX-MULTIPLY-RECURSIVE.A21;B11/ C SQUARE-MATRIX-MULTIPLY-RECURSIVE.A22;B21/ 9 C22 D SQUARE-MATRIX-MULTIPLY-RECURSIVE.A21;B12/ C SQUARE-MATRIX-MULTIPLY-RECURSIVE.A22;B22/ 10 return C This pseudocode glosses over one subtle but important implementation detail. How do we partition the matrices in line 5? If we were to create 12 new n=2 n=2 matrices, we would spend ‚.n2/ time copying entries. In fact, we can partition the matrices without copying entries. The trick is to use index calculations. We identify a submatrix by a range of row indices and a range of column indices of the original matrix. We end up representing a submatrix a little differently from how we represent the original matrix, which is the subtlety we are glossing over. The advantage is that, since we can specify submatrices by index calculations, executing line 5 takes only ‚.1/ time (although we shall see that it makes no difference asymptotically to the overall running time whether we copy or partition in place). Now, we derive a recurrence to characterize the running time of SQUARE- MATRIX-MULTIPLY-RECURSIVE.LetT .n/ be the time to multiply two n n matrices using this procedure. In the base case, when n D 1, we perform just the one scalar multiplication in line 4, and so T.1/D ‚.1/ : (4.15) The recursive case occurs when n>1. As discussed, partitioning the matrices in line 5 takes ‚.1/ time, using index calculations. In lines 6–9, we recursively call SQUARE-MATRIX-MULTIPLY-RECURSIVE a total of eight times. Because each recursive call multiplies two n=2 n=2 matrices, thereby contributing T .n=2/ to the overall running time, the time taken by all eight recursive calls is 8T .n=2/.We also must account for the four matrix additions in lines 6–9. Each of these matrices contains n2=4 entries, and so each of the four matrix additions takes ‚.n2/ time. Since the number of matrix additions is a constant, the total time spent adding ma-78 Chapter 4 Divide-and-Conquer trices in lines 6–9 is ‚.n2/. (Again, we use index calculations to place the results of the matrix additions into the correct positions of matrix C, with an overhead of ‚.1/ time per entry.) The total time for the recursive case, therefore, is the sum of the partitioning time, the time for all the recursive calls, and the time to add the matrices resulting from the recursive calls: T .n/ D ‚.1/ C 8T .n=2/ C ‚.n2/ D 8T .n=2/ C ‚.n2/: (4.16) Notice that if we implemented partitioning by copying matrices, which would cost ‚.n2/ time, the recurrence would not change, and hence the overall running time would increase by only a constant factor. Combining equations (4.15) and (4.16) gives us the recurrence for the running time of SQUARE-MATRIX-MULTIPLY-RECURSIVE: T .n/ D ( ‚.1/ if n D 1; 8T .n=2/ C ‚.n2/ if n>1: (4.17) As we shall see from the master method in Section 4.5, recurrence (4.17) has the solution T .n/ D ‚.n3/. Thus, this simple divide-and-conquer approach is no faster than the straightforward SQUARE-MATRIX-MULTIPLY procedure. Before we continue on to examining Strassen’s algorithm, let us review where the components of equation (4.16) came from. Partitioning each n n matrix by index calculation takes ‚.1/ time, but we have two matrices to partition. Although you could say that partitioning the two matrices takes ‚.2/ time, the constant of 2 is subsumed by the ‚-notation. Adding two matrices, each with, say, k entries, takes ‚.k/ time. Since the matrices we add each have n2=4 entries, you could say that adding each pair takes ‚.n2=4/ time. Again, however, the ‚-notation subsumes the constant factor of 1=4, and we say that adding two n2=4 n2=4 matrices takes ‚.n2/ time. We have four such matrix additions, and once again, instead of saying that they take ‚.4n2/ time, we say that they take ‚.n2/ time. (Of course, you might observe that we could say that the four matrix additions take ‚.4n2=4/ time, and that 4n2=4 D n2, but the point here is that ‚-notation subsumes constant factors, whatever they are.) Thus, we end up with two terms of ‚.n2/, which we can combine into one. When we account for the eight recursive calls, however, we cannot just sub- sume the constant factor of 8. In other words, we must say that together they take 8T .n=2/ time, rather than just T .n=2/ time. You can get a feel for why by looking back at the recursion tree in Figure 2.5, for recurrence (2.1) (which is identical to recurrence (4.7)), with the recursive case T .n/ D 2T .n=2/C‚.n/. The factor of 2 determined how many children each tree node had, which in turn determined how many terms contributed to the sum at each level of the tree. If we were to ignore4.2 Strassen’s algorithm for matrix multiplication 79 the factor of 8 in equation (4.16) or the factor of 2 in recurrence (4.1), the recursion tree would just be linear, rather than “bushy,” and each level would contribute only one term to the sum. Bear in mind, therefore, that although asymptotic notation subsumes constant multiplicative factors, recursive notation such as T .n=2/ does not. Strassen’s method The key to Strassen’s method is to make the recursion tree slightly less bushy. That is, instead of performing eight recursive multiplications of n=2 n=2 matrices, it performs only seven. The cost of eliminating one matrix multiplication will be several new additions of n=2 n=2 matrices, but still only a constant number of additions. As before, the constant number of matrix additions will be subsumed by ‚-notation when we set up the recurrence equation to characterize the running time. Strassen’s method is not at all obvious. (This might be the biggest understate- ment in this book.) It has four steps: 1. Divide the input matrices A and B and output matrix C into n=2 n=2 subma- trices, as in equation (4.9). This step takes ‚.1/ time by index calculation, just as in SQUARE-MATRIX-MULTIPLY-RECURSIVE. 2. Create 10 matrices S1;S2;:::;S10, each of which is n=2 n=2 and is the sum or difference of two matrices created in step 1. We can create all 10 matrices in ‚.n2/ time. 3. Using the submatrices created in step 1 and the 10 matrices created in step 2, recursively compute seven matrix products P1;P2;:::;P7. Each matrix Pi is n=2 n=2. 4. Compute the desired submatrices C11;C12;C21;C22 of the result matrix C by adding and subtracting various combinations of the Pi matrices. We can com- pute all four submatrices in ‚.n2/ time. We shall see the details of steps 2–4 in a moment, but we already have enough information to set up a recurrence for the running time of Strassen’s method. Let us assume that once the matrix size n gets down to 1, we perform a simple scalar mul- tiplication, just as in line 4 of SQUARE-MATRIX-MULTIPLY-RECURSIVE.When n>1, steps 1, 2, and 4 take a total of ‚.n2/ time, and step 3 requires us to per- form seven multiplications of n=2 n=2 matrices. Hence, we obtain the following recurrence for the running time T .n/ of Strassen’s algorithm: T .n/ D ( ‚.1/ if n D 1; 7T .n=2/ C ‚.n2/ if n>1: (4.18)80 Chapter 4 Divide-and-Conquer We have traded off one matrix multiplication for a constant number of matrix ad- ditions. Once we understand recurrences and their solutions, we shall see that this tradeoff actually leads to a lower asymptotic running time. By the master method in Section 4.5, recurrence (4.18) has the solution T .n/ D ‚.nlg 7/. We now proceed to describe the details. In step 2, we create the following 10 matrices: S1 D B12 B22 ; S2 D A11 C A12 ; S3 D A21 C A22 ; S4 D B21 B11 ; S5 D A11 C A22 ; S6 D B11 C B22 ; S7 D A12 A22 ; S8 D B21 C B22 ; S9 D A11 A21 ; S10 D B11 C B12 : Since we must add or subtract n=2 n=2 matrices 10 times, this step does indeed take ‚.n2/ time. In step 3, we recursively multiply n=2n=2 matrices seven times to compute the following n=2 n=2 matrices, each of which is the sum or difference of products of A and B submatrices: P1 D A11 S1 D A11 B12 A11 B22 ; P2 D S2 B22 D A11 B22 C A12 B22 ; P3 D S3 B11 D A21 B11 C A22 B11 ; P4 D A22 S4 D A22 B21 A22 B11 ; P5 D S5 S6 D A11 B11 C A11 B22 C A22 B11 C A22 B22 ; P6 D S7 S8 D A12 B21 C A12 B22 A22 B21 A22 B22 ; P7 D S9 S10 D A11 B11 C A11 B12 A21 B11 A21 B12 : Note that the only multiplications we need to perform are those in the middle col- umn of the above equations. The right-hand column just shows what these products equal in terms of the original submatrices created in step 1. Step 4 adds and subtracts the Pi matrices created in step 3 to construct the four n=2 n=2 submatrices of the product C. We start with C11 D P5 C P4 P2 C P6 :4.2 Strassen’s algorithm for matrix multiplication 81 Expanding out the right-hand side, with the expansion of each Pi on its own line and vertically aligning terms that cancel out, we see that C11 equals A11 B11 CA11 B22 CA22 B11 CA22 B22 A22 B11 CA22 B21 A11 B22 A12 B22 A22 B22 A22 B21 CA12 B22 CA12 B21 A11 B11 CA12 B21 ; which corresponds to equation (4.11). Similarly, we set C12 D P1 C P2 ; and so C12 equals A11 B12 A11 B22 C A11 B22 C A12 B22 A11 B12 C A12 B22 ; corresponding to equation (4.12). Setting C21 D P3 C P4 makes C21 equal A21 B11 C A22 B11 A22 B11 C A22 B21 A21 B11 C A22 B21 ; corresponding to equation (4.13). Finally, we set C22 D P5 C P1 P3 P7 ; so that C22 equals A11 B11 CA11 B22 CA22 B11 CA22 B22 A11 B22 CA11 B12 A22 B11 A21 B11 A11 B11 A11 B12 CA21 B11 CA21 B12 A22 B22 CA21 B12 ;82 Chapter 4 Divide-and-Conquer which corresponds to equation (4.14). Altogether, we add or subtract n=2 n=2 matrices eight times in step 4, and so this step indeed takes ‚.n2/ time. Thus, we see that Strassen’s algorithm, comprising steps 1–4, produces the cor- rect matrix product and that recurrence (4.18) characterizes its running time. Since we shall see in Section 4.5 that this recurrence has the solution T .n/ D ‚.nlg 7/, Strassen’s method is asymptotically faster than the straightforward SQUARE- MATRIX-MULTIPLY procedure. The notes at the end of this chapter discuss some of the practical aspects of Strassen’s algorithm. Exercises Note: Although Exercises 4.2-3, 4.2-4, and 4.2-5 are about variants on Strassen’s algorithm, you should read Section 4.5 before trying to solve them. 4.2-1 Use Strassen’s algorithm to compute the matrix product 13 75 68 42 : Show your work. 4.2-2 Write pseudocode for Strassen’s algorithm. 4.2-3 How would you modify Strassen’s algorithm to multiply nn matrices in which n is not an exact power of 2? Show that the resulting algorithm runs in time ‚.nlg 7/. 4.2-4 What is the largest k such that if you can multiply 3 3 matrices using k multi- plications (not assuming commutativity of multiplication), then you can multiply n n matrices in time o.nlg 7/? What would the running time of this algorithm be? 4.2-5 V. Pan has discovered a way of multiplying 68 68 matrices using 132,464 mul- tiplications, a way of multiplying 70 70 matrices using 143,640 multiplications, and a way of multiplying 72 72 matrices using 155,424 multiplications. Which method yields the best asymptotic running time when used in a divide-and-conquer matrix-multiplication algorithm? How does it compare to Strassen’s algorithm?4.3 The substitution method for solving recurrences 83 4.2-6 How quickly can you multiply a knn matrix by an nknmatrix, using Strassen’s algorithm as a subroutine? Answer the same question with the order of the input matrices reversed. 4.2-7 Show how to multiply the complex numbers a C bi and c C di using only three multiplications of real numbers. The algorithm should take a, b, c,andd as input and produce the real component ac bd and the imaginary component ad C bc separately. 4.3 The substitution method for solving recurrences Now that we have seen how recurrences characterize the running times of divide- and-conquer algorithms, we will learn how to solve recurrences. We start in this section with the “substitution” method. The substitution method for solving recurrences comprises two steps: 1. Guess the form of the solution. 2. Use mathematical induction to ﬁnd the constants and show that the solution works. We substitute the guessed solution for the function when applying the inductive hypothesis to smaller values; hence the name “substitution method.” This method is powerful, but we must be able to guess the form of the answer in order to apply it. We can use the substitution method to establish either upper or lower bounds on a recurrence. As an example, let us determine an upper bound on the recurrence T .n/ D 2T .bn=2c/ C n; (4.19) which is similar to recurrences (4.3) and (4.4). We guess that the solution is T .n/ D O.nlg n/. The substitution method requires us to prove that T .n/ cnlg n for an appropriate choice of the constant c>0. We start by assuming that this bound holds for all positive m*3,the recurrence does not depend directly on T.1/. Thus, we can replace T.1/by T.2/ and T.3/ as the base cases in the inductive proof, letting n0 D 2. Note that we make a distinction between the base case of the recurrence (n D 1) and the base cases of the inductive proof (n D 2 and n D 3). With T.1/ D 1, we derive from the recurrence that T.2/ D 4 and T.3/ D 5. Now we can complete the inductive proof that T .n/ cnlg n for some constant c 1 by choosing c large enough so that T.2/ c2lg 2 and T.3/ c3lg 3. As it turns out, any choice of c 2 sufﬁces for the base cases of n D 2 and n D 3 to hold. For most of the recurrences we shall examine, it is straightforward to extend boundary conditions to make the inductive assumption work for small n, and we shall not always explicitly work out the details. Making a good guess Unfortunately, there is no general way to guess the correct solutions to recurrences. Guessing a solution takes experience and, occasionally, creativity. Fortunately, though, you can use some heuristics to help you become a good guesser. You can also use recursion trees, which we shall see in Section 4.4, to generate good guesses. If a recurrence is similar to one you have seen before, then guessing a similar solution is reasonable. As an example, consider the recurrence T .n/ D 2T .bn=2c C 17/ C n; which looks difﬁcult because of the added “17” in the argument to T on the right- hand side. Intuitively, however, this additional term cannot substantially affect the4.3 The substitution method for solving recurrences 85 solution to the recurrence. When n is large, the difference between bn=2c and bn=2c C 17 is not that large: both cut n nearly evenly in half. Consequently, we make the guess that T .n/ D O.nlg n/, which you can verify as correct by using the substitution method (see Exercise 4.3-6). Another way to make a good guess is to prove loose upper and lower bounds on the recurrence and then reduce the range of uncertainty. For example, we might start with a lower bound of T .n/ D .n/ for the recurrence (4.19), since we have the term n in the recurrence, and we can prove an initial upper bound of T .n/ D O.n2/. Then, we can gradually lower the upper bound and raise the lower bound until we converge on the correct, asymptotically tight solution of T .n/ D ‚.n lg n/. Subtleties Sometimes you might correctly guess an asymptotic bound on the solution of a recurrence, but somehow the math fails to work out in the induction. The problem frequently turns out to be that the inductive assumption is not strong enough to prove the detailed bound. If you revise the guess by subtracting a lower-order term when you hit such a snag, the math often goes through. Consider the recurrence T .n/ D T.bn=2c/ C T.dn=2e/ C 1: We guess that the solution is T .n/ D O.n/, and we try to show that T .n/ cn for an appropriate choice of the constant c. Substituting our guess in the recurrence, we obtain T .n/ c bn=2c C c dn=2e C 1 D cn C 1; which does not imply T .n/ cn for any choice of c. We might be tempted to try a larger guess, say T .n/ D O.n2/. Although we can make this larger guess work, our original guess of T .n/ D O.n/ is correct. In order to show that it is correct, however, we must make a stronger inductive hypothesis. Intuitively, our guess is nearly right: we are off only by the constant 1,a lower-order term. Nevertheless, mathematical induction does not work unless we prove the exact form of the inductive hypothesis. We overcome our difﬁculty by subtracting a lower-order term from our previous guess. Our new guess is T .n/ cn d,whered 0 is a constant. We now have T .n/ .c bn=2c d/C .c dn=2e d/C 1 D cn 2d C 1 cn d;86 Chapter 4 Divide-and-Conquer as long as d 1. As before, we must choose the constant c large enough to handle the boundary conditions. You might ﬁnd the idea of subtracting a lower-order term counterintuitive. Af- ter all, if the math does not work out, we should increase our guess, right? Not necessarily! When proving an upper bound by induction, it may actually be more difﬁcult to prove that a weaker upper bound holds, because in order to prove the weaker bound, we must use the same weaker bound inductively in the proof. In our current example, when the recurrence has more than one recursive term, we get to subtract out the lower-order term of the proposed bound once per recursive term. In the above example, we subtracted out the constant d twice, once for the T.bn=2c/ term and once for the T.dn=2e/ term. We ended up with the inequality T .n/ cn 2d C 1, and it was easy to ﬁnd values of d to make cn 2d C 1 be less than or equal to cn d. Avoiding pitfalls It is easy to err in the use of asymptotic notation. For example, in the recur- rence (4.19) we can falsely “prove” T .n/ D O.n/ by guessing T .n/ cn and then arguing T .n/ 2.c bn=2c/ C n cn C n D O.n/ ; wrong!! since c is a constant. The error is that we have not proved the exact form of the inductive hypothesis, that is, that T .n/ cn. We therefore will explicitly prove that T .n/ cn when we want to show that T .n/ D O.n/. Changing variables Sometimes, a little algebraic manipulation can make an unknown recurrence simi- lar to one you have seen before. As an example, consider the recurrence T .n/ D 2T pn ˘ C lg n; which looks difﬁcult. We can simplify this recurrence, though, with a change of variables. For convenience, we shall not worry about rounding off values, such as pn, to be integers. Renaming m D lg n yields T.2m/ D 2T .2m=2/ C m: We can now rename S.m/ D T.2m/ to produce the new recurrence S.m/ D 2S.m=2/ C m;4.3 The substitution method for solving recurrences 87 which is very much like recurrence (4.19). Indeed, this new recurrence has the same solution: S.m/ D O.mlg m/. Changing back from S.m/ to T .n/, we obtain T .n/ D T.2m/ D S.m/ D O.mlg m/ D O.lg n lg lg n/ : Exercises 4.3-1 Show that the solution of T .n/ D T.n 1/ C n is O.n2/. 4.3-2 Show that the solution of T .n/ D T.dn=2e/ C 1 is O.lg n/. 4.3-3 We saw that the solution of T .n/ D 2T .bn=2c/Cn is O.nlg n/. Show that the so- lution of this recurrence is also .n lg n/. Conclude that the solution is ‚.n lg n/. 4.3-4 Show that by making a different inductive hypothesis, we can overcome the difﬁ- culty with the boundary condition T.1/D 1 for recurrence (4.19) without adjusting the boundary conditions for the inductive proof. 4.3-5 Show that ‚.n lg n/ is the solution to the “exact” recurrence (4.3) for merge sort. 4.3-6 Show that the solution to T .n/ D 2T .bn=2c C 17/ C n is O.nlg n/. 4.3-7 Using the master method in Section 4.5, you can show that the solution to the recurrence T .n/ D 4T .n=3/ C n is T .n/ D ‚.nlog3 4/. Show that a substitution proof with the assumption T .n/ cnlog3 4 fails. Then show how to subtract off a lower-order term to make a substitution proof work. 4.3-8 Using the master method in Section 4.5, you can show that the solution to the recurrence T .n/ D 4T .n=2/ C n2 is T .n/ D ‚.n2/. Show that a substitution proof with the assumption T .n/ cn2 fails. Then show how to subtract off a lower-order term to make a substitution proof work.88 Chapter 4 Divide-and-Conquer 4.3-9 Solve the recurrence T .n/ D 3T .pn/ C log n by making a change of variables. Your solution should be asymptotically tight. Do not worry about whether values are integral. 4.4 The recursion-tree method for solving recurrences Although you can use the substitution method to provide a succinct proof that a solution to a recurrence is correct, you might have trouble coming up with a good guess. Drawing out a recursion tree, as we did in our analysis of the merge sort recurrence in Section 2.3.2, serves as a straightforward way to devise a good guess. In a recursion tree, each node represents the cost of a single subproblem somewhere in the set of recursive function invocations. We sum the costs within each level of the tree to obtain a set of per-level costs, and then we sum all the per-level costs to determine the total cost of all levels of the recursion. A recursion tree is best used to generate a good guess, which you can then verify by the substitution method. When using a recursion tree to generate a good guess, you can often tolerate a small amount of “sloppiness,” since you will be verifying your guess later on. If you are very careful when drawing out a recursion tree and summing the costs, however, you can use a recursion tree as a direct proof of a solution to a recurrence. In this section, we will use recursion trees to generate good guesses, and in Section 4.6, we will use recursion trees directly to prove the theorem that forms the basis of the master method. For example, let us see how a recursion tree would provide a good guess for the recurrence T .n/ D 3T .bn=4c/ C ‚.n2/. We start by focusing on ﬁnding an upper bound for the solution. Because we know that ﬂoors and ceilings usually do not matter when solving recurrences (here’s an example of sloppiness that we can tolerate), we create a recursion tree for the recurrence T .n/ D 3T .n=4/ C cn2, having written out the implied constant coefﬁcient c>0. Figure 4.5 shows how we derive the recursion tree for T .n/ D 3T .n=4/ C cn2. For convenience, we assume that n is an exact power of 4 (another example of tolerable sloppiness) so that all subproblem sizes are integers. Part (a) of the ﬁgure shows T .n/, which we expand in part (b) into an equivalent tree representing the recurrence. The cn2 term at the root represents the cost at the top level of recursion, and the three subtrees of the root represent the costs incurred by the subproblems of size n=4. Part (c) shows this process carried one step further by expanding each node with cost T .n=4/ from part (b). The cost for each of the three children of the root is c.n=4/2. We continue expanding each node in the tree by breaking it into its constituent parts as determined by the recurrence.4.4 The recursion-tree method for solving recurrences 89 … … (d) (c)(b)(a) T .n/ cn2 cn2 cn2 T n 4 T n 4 T n 4 T n 16 T n 16 T n 16 T n 16 T n 16 T n 16 T n 16 T n 16 T n 16 cn2 c n 4 2c n 4 2c n 4 2 c n 4 2c n 4 2c n 4 2 c n 16 2c n 16 2c n 16 2c n 16 2c n 16 2c n 16 2c n 16 2c n 16 2c n 16 2 3 16 cn2 3 16 2 cn2 log4 n nlog4 3 T.1/T.1/T.1/T.1/T.1/T.1/T.1/T.1/T.1/T.1/T.1/T.1/T.1/ ‚.nlog4 3/ Total: O.n2/ Figure 4.5 Constructing a recursion tree for the recurrence T .n/ D 3T .n=4/ C cn2.Part(a) shows T .n/, which progressively expands in (b)–(d) to form the recursion tree. The fully expanded tree in part (d) has height log4 n (it has log4 n C 1 levels).90 Chapter 4 Divide-and-Conquer Because subproblem sizes decrease by a factor of 4 each time we go down one level, we eventually must reach a boundary condition. How far from the root do we reach one? The subproblem size for a node at depth i is n=4i . Thus, the subproblem size hits n D 1 when n=4i D 1 or, equivalently, when i D log4 n. Thus, the tree has log4 n C 1 levels (at depths 0; 1; 2; : : : ; log4 n). Next we determine the cost at each level of the tree. Each level has three times more nodes than the level above, and so the number of nodes at depth i is 3i . Because subproblem sizes reduce by a factor of 4 for each level we go down from the root, each node at depth i,fori D 0; 1; 2; : : : ; log4 n 1,hasacost of c.n=4i /2. Multiplying, we see that the total cost over all nodes at depth i,for i D 0; 1; 2; : : : ; log4 n 1,is3i c.n=4i /2 D .3=16/i cn2. The bottom level, at depth log4 n,has3log4 n D nlog4 3 nodes, each contributing cost T.1/, for a total cost of nlog4 3T.1/,whichis‚.nlog4 3/, since we assume that T.1/is a constant. Now we add up the costs over all levels to determine the cost for the entire tree: T .n/ D cn2 C 3 16 cn2 C 3 16 2 cn2 CC 3 16 log4 n1 cn2 C ‚.nlog4 3/ D log4 n1X iD0 3 16 i cn2 C ‚.nlog4 3/ D .3=16/log4 n 1 .3=16/ 1 cn2 C ‚.nlog4 3/ (by equation (A.5)) : This last formula looks somewhat messy until we realize that we can again take advantage of small amounts of sloppiness and use an inﬁnite decreasing geometric series as an upper bound. Backing up one step and applying equation (A.6), we have T .n/ D log4 n1X iD0 3 16 i cn2 C ‚.nlog4 3/ < 1X iD0 3 16 i cn2 C ‚.nlog4 3/ D 1 1 .3=16/ cn2 C ‚.nlog4 3/ D 16 13 cn2 C ‚.nlog4 3/ D O.n2/: Thus, we have derived a guess of T .n/ D O.n2/ for our original recurrence T .n/ D 3T .bn=4c/ C ‚.n2/. In this example, the coefﬁcients of cn2 form a decreasing geometric series and, by equation (A.6), the sum of these coefﬁcients4.4 The recursion-tree method for solving recurrences 91 … … cn cn cn cn c n 3 c 2n 3 c n 9 c 2n 9 c 2n 9 c 4n 9 log3=2 n Total: O.nlg n/ Figure 4.6 A recursion tree for the recurrence T.n/D T .n=3/ C T .2n=3/ C cn. is bounded from above by the constant 16=13. Since the root’s contribution to the total cost is cn2, the root contributes a constant fraction of the total cost. In other words, the cost of the root dominates the total cost of the tree. In fact, if O.n2/ is indeed an upper bound for the recurrence (as we shall verify in a moment), then it must be a tight bound. Why? The ﬁrst recursive call contributes acostof‚.n2/,andso.n2/ must be a lower bound for the recurrence. Now we can use the substitution method to verify that our guess was cor- rect, that is, T .n/ D O.n2/ is an upper bound for the recurrence T .n/ D 3T .bn=4c/ C ‚.n2/. We want to show that T .n/ dn2 for some constant d>0. Using the same constant c>0as before, we have T .n/ 3T .bn=4c/ C cn2 3d bn=4c2 C cn2 3d.n=4/2 C cn2 D 3 16 dn2 C cn2 dn2 ; where the last step holds as long as d .16=13/c. In another, more intricate, example, Figure 4.6 shows the recursion tree for T .n/ D T .n=3/ C T .2n=3/ C O.n/ : (Again, we omit ﬂoor and ceiling functions for simplicity.) As before, we let c represent the constant factor in the O.n/ term. When we add the values across the levels of the recursion tree shown in the ﬁgure, we get a value of cn for every level.92 Chapter 4 Divide-and-Conquer The longest simple path from the root to a leaf is n ! .2=3/n ! .2=3/2n ! !1.Since.2=3/kn D 1 when k D log3=2 n, the height of the tree is log3=2 n. Intuitively, we expect the solution to the recurrence to be at most the number of levels times the cost of each level, or O.cnlog3=2 n/ D O.nlg n/. Figure 4.6 shows only the top levels of the recursion tree, however, and not every level in the tree contributes a cost of cn. Consider the cost of the leaves. If this recursion tree were a complete binary tree of height log3=2 n, there would be 2log3=2 n D nlog3=2 2 leaves. Since the cost of each leaf is a constant, the total cost of all leaves would then be ‚.nlog3=2 2/ which, since log3=2 2 is a constant strictly greater than 1, is !.nlg n/. This recursion tree is not a complete binary tree, however, and so it has fewer than nlog3=2 2 leaves. Moreover, as we go down from the root, more and more internal nodes are absent. Consequently, levels toward the bottom of the recursion tree contribute less than cn to the total cost. We could work out an accu- rate accounting of all costs, but remember that we are just trying to come up with a guess to use in the substitution method. Let us tolerate the sloppiness and attempt to show that a guess of O.nlg n/ for the upper bound is correct. Indeed, we can use the substitution method to verify that O.nlg n/ is an upper bound for the solution to the recurrence. We show that T .n/ dnlg n,whered is a suitable positive constant. We have T .n/ T .n=3/ C T .2n=3/ C cn d.n=3/ lg.n=3/ C d.2n=3/ lg.2n=3/ C cn D .d.n=3/ lg n d.n=3/ lg 3/ C .d.2n=3/ lg n d.2n=3/ lg.3=2// C cn D dnlg n d..n=3/ lg 3 C .2n=3/ lg.3=2// C cn D dnlg n d..n=3/ lg 3 C .2n=3/ lg 3 .2n=3/ lg 2/ C cn D dnlg n dn.lg 3 2=3/ C cn dnlg n; as long as d c=.lg 3.2=3//. Thus, we did not need to perform a more accurate accounting of costs in the recursion tree. Exercises 4.4-1 Use a recursion tree to determine a good asymptotic upper bound on the recurrence T .n/ D 3T .bn=2c/ C n. Use the substitution method to verify your answer. 4.4-2 Use a recursion tree to determine a good asymptotic upper bound on the recurrence T .n/ D T .n=2/ C n2. Use the substitution method to verify your answer.4.5 The master method for solving recurrences 93 4.4-3 Use a recursion tree to determine a good asymptotic upper bound on the recurrence T .n/ D 4T .n=2 C 2/ C n. Use the substitution method to verify your answer. 4.4-4 Use a recursion tree to determine a good asymptotic upper bound on the recurrence T .n/ D 2T .n 1/ C 1. Use the substitution method to verify your answer. 4.4-5 Use a recursion tree to determine a good asymptotic upper bound on the recurrence T .n/ D T.n1/CT .n=2/Cn. Use the substitution method to verify your answer. 4.4-6 Argue that the solution to the recurrence T .n/ D T .n=3/CT .2n=3/Ccn,wherec is a constant, is .n lg n/ by appealing to a recursion tree. 4.4-7 Draw the recursion tree for T .n/ D 4T .bn=2c/ C cn,wherec is a constant, and provide a tight asymptotic bound on its solution. Verify your bound by the substi- tution method. 4.4-8 Use a recursion tree to give an asymptotically tight solution to the recurrence T .n/ D T.n a/ C T.a/C cn,wherea 1 and c>0are constants. 4.4-9 Use a recursion tree to give an asymptotically tight solution to the recurrence T .n/ D T.˛n/C T ..1 ˛/n/ C cn,where˛ is a constant in the range 0<˛<1 and c>0is also a constant. 4.5 The master method for solving recurrences The master method provides a “cookbook” method for solving recurrences of the form T .n/ D aT .n=b/ C f .n/ ; (4.20) where a 1 and b>1are constants and f .n/ is an asymptotically positive function. To use the master method, you will need to memorize three cases, but then you will be able to solve many recurrences quite easily, often without pencil and paper.94 Chapter 4 Divide-and-Conquer The recurrence (4.20) describes the running time of an algorithm that divides a problem of size n into a subproblems, each of size n=b,wherea and b are positive constants. The a subproblems are solved recursively, each in time T .n=b/.The function f .n/ encompasses the cost of dividing the problem and combining the results of the subproblems. For example, the recurrence arising from Strassen’s algorithm has a D 7, b D 2,andf .n/ D ‚.n2/. As a matter of technical correctness, the recurrence is not actually well deﬁned, because n=b might not be an integer. Replacing each of the a terms T .n=b/ with either T.bn=bc/ or T.dn=be/ will not affect the asymptotic behavior of the recur- rence, however. (We will prove this assertion in the next section.) We normally ﬁnd it convenient, therefore, to omit the ﬂoor and ceiling functions when writing divide-and-conquer recurrences of this form. The master theorem The master method depends on the following theorem. Theorem 4.1 (Master theorem) Let a 1 and b>1be constants, let f .n/ be a function, and let T .n/ be deﬁned on the nonnegative integers by the recurrence T .n/ D aT .n=b/ C f .n/ ; where we interpret n=b to mean either bn=bc or dn=be.ThenT .n/ has the follow- ing asymptotic bounds: 1. If f .n/ D O.nlogb a/ for some constant >0,thenT .n/ D ‚.nlogb a/. 2. If f .n/ D ‚.nlogb a/,thenT .n/ D ‚.nlogb a lg n/. 3. If f .n/ D .nlogb aC/ for some constant >0,andifaf .n=b/ cf .n/ for some constant c<1and all sufﬁciently large n,thenT .n/ D ‚.f .n//. Before applying the master theorem to some examples, let’s spend a moment trying to understand what it says. In each of the three cases, we compare the function f .n/ with the function nlogb a. Intuitively, the larger of the two functions determines the solution to the recurrence. If, as in case 1, the function nlogb a is the larger, then the solution is T .n/ D ‚.nlogb a/. If, as in case 3, the function f .n/ is the larger, then the solution is T .n/ D ‚.f .n//. If, as in case 2, the two func- tions are the same size, we multiply by a logarithmic factor, and the solution is T .n/ D ‚.nlogb a lg n/ D ‚.f .n/ lg n/. Beyond this intuition, you need to be aware of some technicalities. In the ﬁrst case, not only must f .n/ be smaller than nlogb a,itmustbepolynomially smaller.4.5 The master method for solving recurrences 95 That is, f .n/ must be asymptotically smaller than nlogb a by a factor of n for some constant >0. In the third case, not only must f .n/ be larger than nlogb a,italso must be polynomially larger and in addition satisfy the “regularity” condition that af .n=b/ cf .n/. This condition is satisﬁed by most of the polynomially bounded functions that we shall encounter. Note that the three cases do not cover all the possibilities for f .n/. There is a gap between cases 1 and 2 when f .n/ is smaller than nlogb a but not polynomi- ally smaller. Similarly, there is a gap between cases 2 and 3 when f .n/ is larger than nlogb a but not polynomially larger. If the function f .n/ falls into one of these gaps, or if the regularity condition in case 3 fails to hold, you cannot use the master method to solve the recurrence. Using the master method To use the master method, we simply determine which case (if any) of the master theorem applies and write down the answer. As a ﬁrst example, consider T .n/ D 9T .n=3/ C n: For this recurrence, we have a D 9, b D 3, f .n/ D n, and thus we have that nlogb a D nlog3 9 D ‚.n2). Since f .n/ D O.nlog3 9/,where D 1, we can apply case 1 of the master theorem and conclude that the solution is T .n/ D ‚.n2/. Now consider T .n/ D T .2n=3/ C 1; in which a D 1, b D 3=2, f .n/ D 1,andnlogb a D nlog3=2 1 D n0 D 1. Case 2 applies, since f .n/ D ‚.nlogb a/ D ‚.1/, and thus the solution to the recurrence is T .n/ D ‚.lg n/. For the recurrence T .n/ D 3T .n=4/ C n lg n; we have a D 3, b D 4, f .n/ D n lg n,andnlogb a D nlog4 3 D O.n0:793/. Since f .n/ D .nlog4 3C/,where 0:2, case 3 applies if we can show that the regularity condition holds for f .n/. For sufﬁciently large n,wehavethat af .n=b/ D 3.n=4/ lg.n=4/ .3=4/n lg n D cf .n/ for c D 3=4. Consequently, by case 3, the solution to the recurrence is T .n/ D ‚.n lg n/. The master method does not apply to the recurrence T .n/ D 2T .n=2/ C n lg n; even though it appears to have the proper form: a D 2, b D 2, f .n/ D n lg n, and nlogb a D n. You might mistakenly think that case 3 should apply, since96 Chapter 4 Divide-and-Conquer f .n/ D n lg n is asymptotically larger than nlogb a D n. The problem is that it is not polynomially larger. The ratio f .n/=nlogb a D .n lg n/=n D lg n is asymp- totically less than n for any positive constant . Consequently, the recurrence falls into the gap between case 2 and case 3. (See Exercise 4.6-2 for a solution.) Let’s use the master method to solve the recurrences we saw in Sections 4.1 and 4.2. Recurrence (4.7), T .n/ D 2T .n=2/ C ‚.n/ ; characterizes the running times of the divide-and-conquer algorithm for both the maximum-subarray problem and merge sort. (As is our practice, we omit stating the base case in the recurrence.) Here, we have a D 2, b D 2, f .n/ D ‚.n/,and thus we have that nlogb a D nlog2 2 D n. Case 2 applies, since f .n/ D ‚.n/,andso we have the solution T .n/ D ‚.n lg n/. Recurrence (4.17), T .n/ D 8T .n=2/ C ‚.n2/; describes the running time of the ﬁrst divide-and-conquer algorithm that we saw for matrix multiplication. Now we have a D 8, b D 2,andf .n/ D ‚.n2/, and so nlogb a D nlog2 8 D n3.Sincen3 is polynomially larger than f .n/ (that is, f .n/ D O.n3/ for D 1), case 1 applies, and T .n/ D ‚.n3/. Finally, consider recurrence (4.18), T .n/ D 7T .n=2/ C ‚.n2/; which describes the running time of Strassen’s algorithm. Here, we have a D 7, b D 2, f .n/ D ‚.n2/, and thus nlogb a D nlog2 7. Rewriting log2 7 as lg 7 and recalling that 2:80 < lg 7<2:81, we see that f .n/ D O.nlg 7/ for D 0:8. Again, case 1 applies, and we have the solution T .n/ D ‚.nlg 7/. Exercises 4.5-1 Use the master method to give tight asymptotic bounds for the following recur- rences. a. T .n/ D 2T .n=4/ C 1. b. T .n/ D 2T .n=4/ C pn. c. T .n/ D 2T .n=4/ C n. d. T .n/ D 2T .n=4/ C n2.4.6 Proof of the master theorem 97 4.5-2 Professor Caesar wishes to develop a matrix-multiplication algorithm that is asymptotically faster than Strassen’s algorithm. His algorithm will use the divide- and-conquer method, dividing each matrix into pieces of size n=4 n=4,andthe divide and combine steps together will take ‚.n2/ time. He needs to determine how many subproblems his algorithm has to create in order to beat Strassen’s algo- rithm. If his algorithm creates a subproblems, then the recurrence for the running time T .n/ becomes T .n/ D aT .n=4/ C ‚.n2/. What is the largest integer value of a for which Professor Caesar’s algorithm would be asymptotically faster than Strassen’s algorithm? 4.5-3 Use the master method to show that the solution to the binary-search recurrence T .n/ D T .n=2/ C ‚.1/ is T .n/ D ‚.lg n/. (See Exercise 2.3-5 for a description of binary search.) 4.5-4 Can the master method be applied to the recurrence T .n/ D 4T .n=2/ C n2 lg n? Why or why not? Give an asymptotic upper bound for this recurrence. 4.5-5 ? Consider the regularity condition af .n=b/ cf .n/ for some constant c<1, which is part of case 3 of the master theorem. Give an example of constants a 1 and b>1and a function f .n/ that satisﬁes all the conditions in case 3 of the master theorem except the regularity condition. ? 4.6 Proof of the master theorem This section contains a proof of the master theorem (Theorem 4.1). You do not need to understand the proof in order to apply the master theorem. The proof appears in two parts. The ﬁrst part analyzes the master recur- rence (4.20), under the simplifying assumption that T .n/ is deﬁned only on ex- act powers of b>1,thatis,forn D 1; b; b2;:::. This part gives all the intuition needed to understand why the master theorem is true. The second part shows how to extend the analysis to all positive integers n; it applies mathematical technique to the problem of handling ﬂoors and ceilings. In this section, we shall sometimes abuse our asymptotic notation slightly by using it to describe the behavior of functions that are deﬁned only over exact powers of b. Recall that the deﬁnitions of asymptotic notations require that98 Chapter 4 Divide-and-Conquer bounds be proved for all sufﬁciently large numbers, not just those that are pow- ers of b. Since we could make new asymptotic notations that apply only to the set fbi W i D 0; 1; 2; : : :g, instead of to the nonnegative numbers, this abuse is minor. Nevertheless, we must always be on guard when we use asymptotic notation over a limited domain lest we draw improper conclusions. For example, proving that T .n/ D O.n/ when n is an exact power of 2 does not guarantee that T .n/ D O.n/. The function T .n/ could be deﬁned as T .n/ D ( n if n D 1;2;4;8;: : : ; n2 otherwise ; in which case the best upper bound that applies to all values of n is T .n/ D O.n2/. Because of this sort of drastic consequence, we shall never use asymptotic notation over a limited domain without making it absolutely clear from the context that we are doing so. 4.6.1 The proof for exact powers The ﬁrst part of the proof of the master theorem analyzes the recurrence (4.20) T .n/ D aT .n=b/ C f .n/ ; for the master method, under the assumption that n is an exact power of b>1, where b need not be an integer. We break the analysis into three lemmas. The ﬁrst reduces the problem of solving the master recurrence to the problem of evaluating an expression that contains a summation. The second determines bounds on this summation. The third lemma puts the ﬁrst two together to prove a version of the master theorem for the case in which n is an exact power of b. Lemma 4.2 Let a 1 and b>1be constants, and let f .n/ be a nonnegative function deﬁned on exact powers of b.DeﬁneT .n/ on exact powers of b by the recurrence T .n/ D ( ‚.1/ if n D 1; aT .n=b/ C f .n/ if n D bi ; where i is a positive integer. Then T .n/ D ‚.nlogb a/ C logb n1X jD0 aj f .n=bj /: (4.21) Proof We use the recursion tree in Figure 4.7. The root of the tree has cost f .n/, and it has a children, each with cost f .n=b/. (It is convenient to think of a as being4.6 Proof of the master theorem 99 … … … … … … … … … … … … … … … f .n/ f .n/ aaa a aaa a aaa a a f .n=b/f .n=b/f .n=b/ f .n=b2/f .n=b2/f .n=b2/f .n=b2/f .n=b2/f .n=b2/f .n=b2/f .n=b2/f .n=b2/ af .n=b/ a2f .n=b2/ logb n nlogb a ‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/ ‚.nlogb a/ Total: ‚.nlogb a/ C logb n1X jD0 aj f .n=bj / Figure 4.7 The recursion tree generated by T .n/ D aT .n=b/Cf .n/. The tree is a complete a-ary tree with nlogb a leaves and height logb n. The cost of the nodes at each depth is shown at the right, and their sum is given in equation (4.21). an integer, especially when visualizing the recursion tree, but the mathematics does not require it.) Each of these children has a children, making a2 nodes at depth 2, and each of the a children has cost f .n=b2/. In general, there are aj nodes at depth j , and each has cost f .n=bj /. The cost of each leaf is T.1/ D ‚.1/,and each leaf is at depth logb n,sincen=blogb n D 1.Therearealogb n D nlogb a leaves in the tree. We can obtain equation (4.21) by summing the costs of the nodes at each depth in the tree, as shown in the ﬁgure. The cost for all internal nodes at depth j is aj f .n=bj /, and so the total cost of all internal nodes is logb n1X jD0 aj f .n=bj /: In the underlying divide-and-conquer algorithm, this sum represents the costs of dividing problems into subproblems and then recombining the subproblems. The100 Chapter 4 Divide-and-Conquer cost of all the leaves, which is the cost of doing all nlogb a subproblems of size 1, is ‚.nlogb a/. In terms of the recursion tree, the three cases of the master theorem correspond to cases in which the total cost of the tree is (1) dominated by the costs in the leaves, (2) evenly distributed among the levels of the tree, or (3) dominated by the cost of the root. The summation in equation (4.21) describes the cost of the dividing and com- bining steps in the underlying divide-and-conquer algorithm. The next lemma pro- vides asymptotic bounds on the summation’s growth. Lemma 4.3 Let a 1 and b>1be constants, and let f .n/ be a nonnegative function deﬁned on exact powers of b. A function g.n/ deﬁned over exact powers of b by g.n/ D logb n1X jD0 aj f .n=bj / (4.22) has the following asymptotic bounds for exact powers of b: 1. If f .n/ D O.nlogb a/ for some constant >0,theng.n/ D O.nlogb a/. 2. If f .n/ D ‚.nlogb a/,theng.n/ D ‚.nlogb a lg n/. 3. If af .n=b/ cf .n/ for some constant c<1and for all sufﬁciently large n, then g.n/ D ‚.f .n//. Proof For case 1, we have f .n/ D O.nlogb a/, which implies that f .n=bj / D O..n=bj /logb a/. Substituting into equation (4.22) yields g.n/ D O logb n1X jD0 aj n bj logb a ! : (4.23) We bound the summation within the O-notation by factoring out terms and simpli- fying, which leaves an increasing geometric series: logb n1X jD0 aj n bj logb a D nlogb a logb n1X jD0 ab blogb a j D nlogb a logb n1X jD0 .b/j D nlogb a b logb n 1 b 1 4.6 Proof of the master theorem 101 D nlogb a n 1 b 1 : Since b and are constants, we can rewrite the last expression as nlogb aO.n/ D O.nlogb a/. Substituting this expression for the summation in equation (4.23) yields g.n/ D O.nlogb a/; thereby proving case 1. Because case 2 assumes that f .n/ D ‚.nlogb a/,wehavethatf .n=bj / D ‚..n=bj /logb a/. Substituting into equation (4.22) yields g.n/ D ‚ logb n1X jD0 aj n bj logb a ! : (4.24) We bound the summation within the ‚-notation as in case 1, but this time we do not obtain a geometric series. Instead, we discover that every term of the summation is the same: logb n1X jD0 aj n bj logb a D nlogb a logb n1X jD0 a blogb a j D nlogb a logb n1X jD0 1 D nlogb a logb n: Substituting this expression for the summation in equation (4.24) yields g.n/ D ‚.nlogb a logb n/ D ‚.nlogb a lg n/ ; proving case 2. We prove case 3 similarly. Since f .n/ appears in the deﬁnition (4.22) of g.n/ and all terms of g.n/ are nonnegative, we can conclude that g.n/ D .f .n// for exact powers of b. We assume in the statement of the lemma that af .n=b/ cf .n/ for some constant c<1and all sufﬁciently large n. We rewrite this assumption as f .n=b/ .c=a/f .n/ and iterate j times, yielding f .n=bj / .c=a/j f .n/ or, equivalently, aj f .n=bj / cj f .n/, where we assume that the values we iterate on are sufﬁciently large. Since the last, and smallest, such value is n=bj1,itis enough to assume that n=bj1 is sufﬁciently large. Substituting into equation (4.22) and simplifying yields a geometric series, but unlike the series in case 1, this one has decreasing terms. We use an O.1/ term to102 Chapter 4 Divide-and-Conquer capture the terms that are not covered by our assumption that n is sufﬁciently large: g.n/ D logb n1X jD0 aj f .n=bj / logb n1X jD0 cj f .n/ C O.1/ f .n/ 1X jD0 cj C O.1/ D f .n/ 1 1 c C O.1/ D O.f .n// ; since c is a constant. Thus, we can conclude that g.n/ D ‚.f .n// for exact powers of b. With case 3 proved, the proof of the lemma is complete. We can now prove a version of the master theorem for the case in which n is an exact power of b. Lemma 4.4 Let a 1 and b>1be constants, and let f .n/ be a nonnegative function deﬁned on exact powers of b.DeﬁneT .n/ on exact powers of b by the recurrence T .n/ D ( ‚.1/ if n D 1; aT .n=b/ C f .n/ if n D bi ; where i is a positive integer. Then T .n/ has the following asymptotic bounds for exact powers of b: 1. If f .n/ D O.nlogb a/ for some constant >0,thenT .n/ D ‚.nlogb a/. 2. If f .n/ D ‚.nlogb a/,thenT .n/ D ‚.nlogb a lg n/. 3. If f .n/ D .nlogb aC/ for some constant >0,andifaf .n=b/ cf .n/ for some constant c<1and all sufﬁciently large n,thenT .n/ D ‚.f .n//. Proof We use the bounds in Lemma 4.3 to evaluate the summation (4.21) from Lemma 4.2. For case 1, we have T .n/ D ‚.nlogb a/ C O.nlogb a/ D ‚.nlogb a/;4.6 Proof of the master theorem 103 and for case 2, T .n/ D ‚.nlogb a/ C ‚.nlogb a lg n/ D ‚.nlogb a lg n/ : For case 3, T .n/ D ‚.nlogb a/ C ‚.f .n// D ‚.f .n// ; because f .n/ D .nlogb aC/. 4.6.2 Floors and ceilings To complete the proof of the master theorem, we must now extend our analysis to the situation in which ﬂoors and ceilings appear in the master recurrence, so that the recurrence is deﬁned for all integers, not for just exact powers of b. Obtaining a lower bound on T .n/ D aT.dn=be/ C f .n/ (4.25) and an upper bound on T .n/ D aT.bn=bc/ C f .n/ (4.26) is routine, since we can push through the bound dn=be n=b in the ﬁrst case to yield the desired result, and we can push through the bound bn=bc n=b in the second case. We use much the same technique to lower-bound the recurrence (4.26) as to upper-bound the recurrence (4.25), and so we shall present only this latter bound. We modify the recursion tree of Figure 4.7 to produce the recursion tree in Fig- ure 4.8. As we go down in the recursion tree, we obtain a sequence of recursive invocations on the arguments n; dn=be ; ddn=be =be ; dddn=be =be =be ; ::: Let us denote the j th element in the sequence by nj ,where nj D ( n if j D 0; dnj1=be if j>0: (4.27)104 Chapter 4 Divide-and-Conquer … … … … … … … … … … … … … … … f .n/ f .n/ aaa a aaa a aaa a a f.n1/f.n1/f.n1/ f.n2/f.n2/f.n2/f.n2/f.n2/f.n2/f.n2/f.n2/f.n2/ af .n 1/ a2f.n2/ blogb nc ‚.nlogb a/ ‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/‚.1/ ‚.nlogb a/ Total: ‚.nlogb a/ C blogb nc1X jD0 aj f.nj / Figure 4.8 The recursion tree generated by T .n/ D aT .dn=be/Cf .n/. The recursive argument nj is given by equation (4.27). Our ﬁrst goal is to determine the depth k such that nk is a constant. Using the inequality dxe x C 1, we obtain n0 n; n1 n b C 1; n2 n b2 C 1 b C 1; n3 n b3 C 1 b2 C 1 b C 1; ::: In general, we have4.6 Proof of the master theorem 105 nj n bj C j1X iD0 1 bi < n bj C 1X iD0 1 bi D n bj C b b 1 : Letting j D blogb nc, we obtain nblogb nc < n bblogb nc C b b 1 < n blogb n1 C b b 1 D n n=b C b b 1 D b C b b 1 D O.1/ ; and thus we see that at depth blogb nc, the problem size is at most a constant. From Figure 4.8, we see that T .n/ D ‚.nlogb a/ C blogb nc1X jD0 aj f.nj /; (4.28) which is much the same as equation (4.21), except that n is an arbitrary integer and not restricted to be an exact power of b. We can now evaluate the summation g.n/ D blogb nc1X jD0 aj f.nj / (4.29) from equation (4.28) in a manner analogous to the proof of Lemma 4.3. Beginning with case 3, if af .dn=be/ cf .n/ for n>bCb=.b1/,wherec<1is a constant, then it follows that aj f.nj / cj f .n/. Therefore, we can evaluate the sum in equation (4.29) just as in Lemma 4.3. For case 2, we have f .n/ D ‚.nlogb a/.Ifwe can show that f.nj / D O.nlogb a=aj / D O..n=bj /logb a/, then the proof for case 2 of Lemma 4.3 will go through. Observe that j blogb nc implies bj =n 1.The bound f .n/ D O.nlogb a/ implies that there exists a constant c>0such that for all sufﬁciently large nj ,106 Chapter 4 Divide-and-Conquer f.nj / c n bj C b b 1 logb a D c n bj 1 C bj n b b 1 logb a D c nlogb a aj 1 C bj n b b 1 logb a c nlogb a aj 1 C b b 1 logb a D O nlogb a aj ; since c.1 C b=.b 1//logb a is a constant. Thus, we have proved case 2. The proof of case 1 is almost identical. The key is to prove the bound f.nj / D O.nlogb a/, which is similar to the corresponding proof of case 2, though the algebra is more intricate. We have now proved the upper bounds in the master theorem for all integers n. The proof of the lower bounds is similar. Exercises 4.6-1 ? Give a simple and exact expression for nj in equation (4.27) for the case in which b is a positive integer instead of an arbitrary real number. 4.6-2 ? Show that if f .n/ D ‚.nlogb a lgk n/,wherek 0, then the master recurrence has solution T .n/ D ‚.nlogb a lgkC1 n/. For simplicity, conﬁne your analysis to exact powers of b. 4.6-3 ? Show that case 3 of the master theorem is overstated, in the sense that the regularity condition af .n=b/ cf .n/ for some constant c<1implies that there exists a constant >0such that f .n/ D .nlogb aC/.Problems for Chapter 4 107 Problems 4-1 Recurrence examples Give asymptotic upper and lower bounds for T .n/ in each of the following recur- rences. Assume that T .n/ is constant for n 2. Make your bounds as tight as possible, and justify your answers. a. T .n/ D 2T .n=2/ C n4. b. T .n/ D T .7n=10/ C n. c. T .n/ D 16T .n=4/ C n2. d. T .n/ D 7T .n=3/ C n2. e. T .n/ D 7T .n=2/ C n2. f. T .n/ D 2T .n=4/ C pn. g. T .n/ D T.n 2/ C n2. 4-2 Parameter-passing costs Throughout this book, we assume that parameter passing during procedure calls takes constant time, even if an N -element array is being passed. This assumption is valid in most systems because a pointer to the array is passed, not the array itself. This problem examines the implications of three parameter-passing strategies: 1. An array is passed by pointer. Time D ‚.1/. 2. An array is passed by copying. Time D ‚.N /,whereN is the size of the array. 3. An array is passed by copying only the subrange that might be accessed by the called procedure. Time D ‚.q p C 1/ if the subarray AŒp : : q is passed. a. Consider the recursive binary search algorithm for ﬁnding a number in a sorted array (see Exercise 2.3-5). Give recurrences for the worst-case running times of binary search when arrays are passed using each of the three methods above, and give good upper bounds on the solutions of the recurrences. Let N be the size of the original problem and n be the size of a subproblem. b. Redo part (a) for the MERGE-SORT algorithm from Section 2.3.1.108 Chapter 4 Divide-and-Conquer 4-3 More recurrence examples Give asymptotic upper and lower bounds for T .n/ in each of the following recur- rences. Assume that T .n/ is constant for sufﬁciently small n. Make your bounds as tight as possible, and justify your answers. a. T .n/ D 4T .n=3/ C n lg n. b. T .n/ D 3T .n=3/ C n= lg n. c. T .n/ D 4T .n=2/ C n2pn. d. T .n/ D 3T .n=3 2/ C n=2. e. T .n/ D 2T .n=2/ C n= lg n. f. T .n/ D T .n=2/ C T .n=4/ C T .n=8/ C n. g. T .n/ D T.n 1/ C 1=n. h. T .n/ D T.n 1/ C lg n. i. T .n/ D T.n 2/ C 1= lg n. j. T .n/ D pnT .pn/ C n. 4-4 Fibonacci numbers This problem develops properties of the Fibonacci numbers, which are deﬁned by recurrence (3.22). We shall use the technique of generating functions to solve the Fibonacci recurrence. Deﬁne the generating function (or formal power se- ries) F as F .´/ D 1X iD0 Fi ´i D 0 C ´ C ´2 C 2´3 C 3´4 C 5´5 C 8´6 C 13´7 C 21´8 C ; where Fi is the ith Fibonacci number. a. Show that F .´/ D ´ C ´F .´/ C ´2F .´/.Problems for Chapter 4 109 b. Show that F .´/ D ´ 1 ´ ´2 D ´ .1 ´/.1 y´/ D 1p 5 1 1 ´ 1 1 y´ ; where D 1 C p 5 2 D 1:61803 : : : and y D 1 p 5 2 D0:61803 : : : : c. Show that F .´/ D 1X iD0 1p 5 .i yi /´i : d. Use part (c) to prove that Fi D i = p 5 for i>0, rounded to the nearest integer. (Hint: Observe that ˇˇy ˇˇ <1.) 4-5 Chip testing Professor Diogenes has n supposedly identical integrated-circuit chips that in prin- ciple are capable of testing each other. The professor’s test jig accommodates two chips at a time. When the jig is loaded, each chip tests the other and reports whether it is good or bad. A good chip always reports accurately whether the other chip is good or bad, but the professor cannot trust the answer of a bad chip. Thus, the four possible outcomes of a test are as follows: Chip A says Chip B says Conclusion B is good A is good both are good, or both are bad B is good A is bad at least one is bad B is bad A is good at least one is bad B is bad A is bad at least one is bad a. Show that if more than n=2 chips are bad, the professor cannot necessarily de- termine which chips are good using any strategy based on this kind of pairwise test. Assume that the bad chips can conspire to fool the professor.110 Chapter 4 Divide-and-Conquer b. Consider the problem of ﬁnding a single good chip from among n chips, as- suming that more than n=2 of the chips are good. Show that bn=2c pairwise tests are sufﬁcient to reduce the problem to one of nearly half the size. c. Show that the good chips can be identiﬁed with ‚.n/ pairwise tests, assuming that more than n=2 of the chips are good. Give and solve the recurrence that describes the number of tests. 4-6 Monge arrays An m n array A of real numbers is a Monge array if for all i, j , k,andl such that 1 ix0 ; (4.30) where x 1 is a real number, x0 is a constant such that x0 1=bi and x0 1=.1 bi / for i D 1;2;:::;k, ai is a positive constant for i D 1;2;:::;k,Notes for Chapter 4 113 bi is a constant in the range 0 AŒj ,then the pair .i; j / is called an inversion of A. (See Problem 2-4 for more on inver- sions.) Suppose that the elements of A form a uniform random permutation of h1;2;:::;ni. Use indicator random variables to compute the expected number of inversions. 5.3 Randomized algorithms In the previous section, we showed how knowing a distribution on the inputs can help us to analyze the average-case behavior of an algorithm. Many times, we do not have such knowledge, thus precluding an average-case analysis. As mentioned in Section 5.1, we may be able to use a randomized algorithm. For a problem such as the hiring problem, in which it is helpful to assume that all permutations of the input are equally likely, a probabilistic analysis can guide the development of a randomized algorithm. Instead of assuming a distribution of inputs, we impose a distribution. In particular, before running the algorithm, we randomly permute the candidates in order to enforce the property that every permutation is equally likely. Although we have modiﬁed the algorithm, we still expect to hire a new ofﬁce assistant approximately ln n times. But now we expect5.3 Randomized algorithms 123 this to be the case for any input, rather than for inputs drawn from a particular distribution. Let us further explore the distinction between probabilistic analysis and random- ized algorithms. In Section 5.2, we claimed that, assuming that the candidates ar- rive in a random order, the expected number of times we hire a new ofﬁce assistant is about ln n. Note that the algorithm here is deterministic; for any particular input, the number of times a new ofﬁce assistant is hired is always the same. Furthermore, the number of times we hire a new ofﬁce assistant differs for different inputs, and it depends on the ranks of the various candidates. Since this number depends only on the ranks of the candidates, we can represent a particular input by listing, in order, the ranks of the candidates, i.e., hrank.1/; rank.2/;:::;rank.n/i. Given the rank list A1 Dh1; 2; 3; 4; 5; 6; 7; 8; 9; 10i, a new ofﬁce assistant is always hired 10 times, since each successive candidate is better than the previous one, and lines 5–6 are executed in each iteration. Given the list of ranks A2 Dh10; 9; 8; 7; 6; 5; 4; 3; 2; 1i, a new ofﬁce assistant is hired only once, in the ﬁrst iteration. Given a list of ranks A3 Dh5; 2; 1; 8; 4; 7; 10; 9; 3; 6i, a new ofﬁce assistant is hired three times, upon interviewing the candidates with ranks 5, 8,and10. Recalling that the cost of our algorithm depends on how many times we hire a new ofﬁce assistant, we see that there are expensive inputs such as A1, inexpensive inputs such as A2,and moderately expensive inputs such as A3. Consider, on the other hand, the randomized algorithm that ﬁrst permutes the candidates and then determines the best candidate. In this case, we randomize in the algorithm, not in the input distribution. Given a particular input, say A3 above, we cannot say how many times the maximum is updated, because this quantity differs with each run of the algorithm. The ﬁrst time we run the algorithm on A3, it may produce the permutation A1 and perform 10 updates; but the second time we run the algorithm, we may produce the permutation A2 and perform only one update. The third time we run it, we may perform some other number of updates. Each time we run the algorithm, the execution depends on the random choices made and is likely to differ from the previous execution of the algorithm. For this algorithm and many other randomized algorithms, no particular input elicits its worst-case behavior. Even your worst enemy cannot produce a bad input array, since the random permutation makes the input order irrelevant. The randomized algorithm performs badly only if the random-number generator produces an “un- lucky” permutation. For the hiring problem, the only change needed in the code is to randomly per- mute the array.124 Chapter 5 Probabilistic Analysis and Randomized Algorithms RANDOMIZED-HIRE-ASSISTANT.n/ 1 randomly permute the list of candidates 2 best D 0 // candidate 0 is a least-qualiﬁed dummy candidate 3 for i D 1 to n 4 interview candidate i 5 if candidate i is better than candidate best 6 best D i 7 hire candidate i With this simple change, we have created a randomized algorithm whose perfor- mance matches that obtained by assuming that the candidates were presented in a random order. Lemma 5.3 The expected hiring cost of the procedure RANDOMIZED-HIRE-ASSISTANT is O.ch ln n/. Proof After permuting the input array, we have achieved a situation identical to that of the probabilistic analysis of HIRE-ASSISTANT. Comparing Lemmas 5.2 and 5.3 highlights the difference between probabilistic analysis and randomized algorithms. In Lemma 5.2, we make an assumption about the input. In Lemma 5.3, we make no such assumption, although randomizing the input takes some additional time. To remain consistent with our terminology, we couched Lemma 5.2 in terms of the average-case hiring cost and Lemma 5.3 in terms of the expected hiring cost. In the remainder of this section, we discuss some issues involved in randomly permuting inputs. Randomly permuting arrays Many randomized algorithms randomize the input by permuting the given input array. (There are other ways to use randomization.) Here, we shall discuss two methods for doing so. We assume that we are given an array A which, without loss of generality, contains the elements 1 through n. Our goal is to produce a random permutation of the array. One common method is to assign each element AŒi of the array a random pri- ority PŒi, and then sort the elements of A according to these priorities. For ex- ample, if our initial array is A Dh1; 2; 3; 4i and we choose random priorities P Dh36; 3; 62; 19i, we would produce an array B Dh2;4;1;3i, since the second priority is the smallest, followed by the fourth, then the ﬁrst, and ﬁnally the third. We call this procedure PERMUTE-BY-SORTING:5.3 Randomized algorithms 125 PERMUTE-BY-SORTING.A/ 1 n D A:length 2letPŒ1::nbe a new array 3 for i D 1 to n 4 PŒi D RANDOM.1; n3/ 5sortA,usingP as sort keys Line 4 chooses a random number between 1 and n3. We use a range of 1 to n3 to make it likely that all the priorities in P are unique. (Exercise 5.3-5 asks you to prove that the probability that all entries are unique is at least 1 1=n,and Exercise 5.3-6 asks how to implement the algorithm even if two or more priorities are identical.) Let us assume that all the priorities are unique. The time-consuming step in this procedure is the sorting in line 5. As we shall see in Chapter 8, if we use a comparison sort, sorting takes .n lg n/ time. We can achieve this lower bound, since we have seen that merge sort takes ‚.n lg n/ time. (We shall see other comparison sorts that take ‚.n lg n/ time in Part II. Exercise 8.3-4 asks you to solve the very similar problem of sorting numbers in the range 0 to n3 1 in O.n/ time.) After sorting, if PŒiis the j th smallest priority, then AŒi lies in position j of the output. In this manner we obtain a permutation. It remains to prove that the procedure produces a uniform random permutation,that is, that the procedure is equally likely to produce every permutation of the numbers 1 through n. Lemma 5.4 Procedure PERMUTE-BY-SORTING produces a uniform random permutation of the input, assuming that all priorities are distinct. Proof We start by considering the particular permutation in which each ele- ment AŒi receives the ith smallest priority. We shall show that this permutation occurs with probability exactly 1=nŠ.Fori D 1;2;:::;n,letEi be the event that element AŒi receives the ith smallest priority. Then we wish to compute the probability that for all i,eventEi occurs, which is Pr fE1 \ E2 \ E3 \\En1 \ Eng : Using Exercise C.2-5, this probability is equal to Pr fE1g Pr fE2 j E1g Pr fE3 j E2 \ E1g Pr fE4 j E3 \ E2 \ E1g Pr fEi j Ei1 \ Ei2 \\E1g Pr fEn j En1 \\E1g : We have that Pr fE1g D 1=n because it is the probability that one priority chosen randomly out of a set of n is the smallest priority. Next, we observe126 Chapter 5 Probabilistic Analysis and Randomized Algorithms that Pr fE2 j E1g D 1=.n 1/ because given that element AŒ1 has the small- est priority, each of the remaining n 1 elements has an equal chance of hav- ing the second smallest priority. In general, for i D 2;3;:::;n,wehavethat Pr fEi j Ei1 \ Ei2 \\E1g D 1=.ni C1/, since, given that elements AŒ1 through AŒi 1 have the i 1 smallest priorities (in order), each of the remaining n .i 1/ elements has an equal chance of having the ith smallest priority. Thus, we have Pr fE1 \ E2 \ E3 \\En1 \ Eng D 1 n 1 n 1 1 2 1 1 D 1 nŠ ; and we have shown that the probability of obtaining the identity permutation is 1=nŠ. We can extend this proof to work for any permutation of priorities. Consider any ﬁxed permutation Dh.1/; .2/; : : : ; .n/i of the set f1;2;:::;ng.Letus denote by ri the rank of the priority assigned to element AŒi, where the element with the j th smallest priority has rank j .IfwedeﬁneEi as the event in which element AŒi receives the .i/th smallest priority, or ri D .i/, the same proof still applies. Therefore, if we calculate the probability of obtaining any particular permutation, the calculation is identical to the one above, so that the probability of obtaining this permutation is also 1=nŠ. You might think that to prove that a permutation is a uniform random permuta- tion, it sufﬁces to show that, for each element AŒi, the probability that the element winds up in position j is 1=n. Exercise 5.3-4 shows that this weaker condition is, in fact, insufﬁcient. A better method for generating a random permutation is to permute the given array in place. The procedure RANDOMIZE-IN-PLACE does so in O.n/ time. In its ith iteration, it chooses the element AŒi randomly from among elements AŒi through AŒn. Subsequent to the ith iteration, AŒi is never altered. RANDOMIZE-IN-PLACE.A/ 1 n D A:length 2 for i D 1 to n 3swapAŒi with AŒRANDOM.i; n/ We shall use a loop invariant to show that procedure RANDOMIZE-IN-PLACE produces a uniform random permutation. A k-permutation on a set of n ele- ments is a sequence containing k of the n elements, with no repetitions. (See Appendix C.) There are nŠ=.n k/Š such possible k-permutations.5.3 Randomized algorithms 127 Lemma 5.5 Procedure RANDOMIZE-IN-PLACE computes a uniform random permutation. Proof We use the following loop invariant: Just prior to the ith iteration of the for loop of lines 2–3, for each possible .i 1/-permutation of the n elements, the subarray AŒ1 : : i 1 contains this .i 1/-permutation with probability .n i C 1/Š=nŠ. We need to show that this invariant is true prior to the ﬁrst loop iteration, that each iteration of the loop maintains the invariant, and that the invariant provides a useful property to show correctness when the loop terminates. Initialization: Consider the situation just before the ﬁrst loop iteration, so that i D 1. The loop invariant says that for each possible 0-permutation, the sub- array AŒ1 : : 0 contains this 0-permutation with probability .n i C 1/Š=nŠ D nŠ=nŠ D 1. The subarray AŒ1 : : 0 is an empty subarray, and a 0-permutation has no elements. Thus, AŒ1 : : 0 contains any 0-permutation with probability 1, and the loop invariant holds prior to the ﬁrst iteration. Maintenance: We assume that just before the ith iteration, each possible .i 1/-permutation appears in the subarray AŒ1 : : i 1 with probability .n i C 1/Š=nŠ, and we shall show that after the ith iteration, each possible i-permutation appears in the subarray AŒ1 : : i with probability .n i/Š=nŠ. Incrementing i for the next iteration then maintains the loop invariant. Let us examine the ith iteration. Consider a particular i-permutation, and de- note the elements in it by hx1;x2;:::;xi i. This permutation consists of an .i 1/-permutation hx1;:::;xi1i followed by the value xi that the algorithm places in AŒi.LetE1 denote the event in which the ﬁrst i 1 iterations have created the particular .i 1/-permutation hx1;:::;xi1i in AŒ1 : : i 1.Bythe loop invariant, Pr fE1g D .n i C 1/Š=nŠ.LetE2 be the event that ith iteration puts xi in position AŒi.Thei-permutation hx1;:::;xi i appears in AŒ1 : : i pre- cisely when both E1 and E2 occur, and so we wish to compute Pr fE2 \ E1g. Using equation (C.14), we have Pr fE2 \ E1g D Pr fE2 j E1g Pr fE1g : The probability Pr fE2 j E1g equals 1=.niC1/ because in line 3 the algorithm chooses xi randomly from the n i C 1 values in positions AŒi : : n. Thus, we have128 Chapter 5 Probabilistic Analysis and Randomized Algorithms Pr fE2 \ E1g D Pr fE2 j E1g Pr fE1g D 1 n i C 1 .n i C 1/Š nŠ D .n i/Š nŠ : Termination: At termination, i D n C 1, and we have that the subarray AŒ1 : : n is a given n-permutation with probability .n.nC1/C1/=nŠ D 0Š=nŠ D 1=nŠ. Thus, RANDOMIZE-IN-PLACE produces a uniform random permutation. A randomized algorithm is often the simplest and most efﬁcient way to solve a problem. We shall use randomized algorithms occasionally throughout this book. Exercises 5.3-1 Professor Marceau objects to the loop invariant used in the proof of Lemma 5.5. He questions whether it is true prior to the ﬁrst iteration. He reasons that we could just as easily declare that an empty subarray contains no 0-permutations. Therefore, the probability that an empty subarray contains a 0-permutation should be 0, thus invalidating the loop invariant prior to the ﬁrst iteration. Rewrite the procedure RANDOMIZE-IN-PLACE so that its associated loop invariant applies to a nonempty subarray prior to the ﬁrst iteration, and modify the proof of Lemma 5.5 for your procedure. 5.3-2 Professor Kelp decides to write a procedure that produces at random any permuta- tion besides the identity permutation. He proposes the following procedure: PERMUTE-WITHOUT-IDENTITY.A/ 1 n D A:length 2 for i D 1 to n 1 3swapAŒi with AŒRANDOM.i C 1; n/ Does this code do what Professor Kelp intends? 5.3-3 Suppose that instead of swapping element AŒi with a random element from the subarray AŒi : : n, we swapped it with a random element from anywhere in the array:5.3 Randomized algorithms 129 PERMUTE-WITH-ALL.A/ 1 n D A:length 2 for i D 1 to n 3swapAŒi with AŒRANDOM.1; n/ Does this code produce a uniform random permutation? Why or why not? 5.3-4 Professor Armstrong suggests the following procedure for generating a uniform random permutation: PERMUTE-BY-CYCLIC.A/ 1 n D A:length 2letBŒ1::nbe a new array 3 offset D RANDOM.1; n/ 4 for i D 1 to n 5 dest D i C offset 6 if dest >n 7 dest D dest n 8 BŒdest D AŒi 9 return B Show that each element AŒi has a 1=n probability of winding up in any particular position in B. Then show that Professor Armstrong is mistaken by showing that the resulting permutation is not uniformly random. 5.3-5 ? Prove that in the array P in procedure PERMUTE-BY-SORTING, the probability that all elements are unique is at least 1 1=n. 5.3-6 Explain how to implement the algorithm PERMUTE-BY-SORTING to handle the case in which two or more priorities are identical. That is, your algorithm should produce a uniform random permutation, even if two or more priorities are identical. 5.3-7 Suppose we want to create a random sample of the set f1; 2; 3; : : : ; ng,thatis, an m-element subset S,where0 m n, such that each m-subset is equally likely to be created. One way would be to set AŒi D i for i D 1; 2; 3; : : : ; n, call RANDOMIZE-IN-PLACE.A/, and then take just the ﬁrst m array elements. This method would make n calls to the RANDOM procedure. If n is much larger than m, we can create a random sample with fewer calls to RANDOM. Show that130 Chapter 5 Probabilistic Analysis and Randomized Algorithms the following recursive procedure returns a random m-subset S of f1; 2; 3; : : : ; ng, in which each m-subset is equally likely, while making only m calls to RANDOM: RANDOM-SAMPLE.m; n/ 1 if m == 0 2 return ; 3 else S D RANDOM-SAMPLE.m 1; n 1/ 4 i D RANDOM.1; n/ 5 if i 2 S 6 S D S [ fng 7 else S D S [ fig 8 return S ? 5.4 Probabilistic analysis and further uses of indicator random variables This advanced section further illustrates probabilistic analysis by way of four ex- amples. The ﬁrst determines the probability that in a room of k people, two of them share the same birthday. The second example examines what happens when we randomly toss balls into bins. The third investigates “streaks” of consecutive heads when we ﬂip coins. The ﬁnal example analyzes a variant of the hiring prob- lem in which you have to make decisions without actually interviewing all the candidates. 5.4.1 The birthday paradox Our ﬁrst example is the birthday paradox. How many people must there be in a room before there is a 50% chance that two of them were born on the same day of the year? The answer is surprisingly few. The paradox is that it is in fact far fewer than the number of days in a year, or even half the number of days in a year, as we shall see. To answer this question, we index the people in the room with the integers 1;2;:::;k,wherek is the number of people in the room. We ignore the issue of leap years and assume that all years have n D 365 days. For i D 1;2;:::;k, let bi be the day of the year on which person i’s birthday falls, where 1 bi n. We also assume that birthdays are uniformly distributed across the n days of the year, so that Pr fbi D rg D 1=n for i D 1;2;:::;kand r D 1;2;:::;n. The probability that two given people, say i and j , have matching birthdays depends on whether the random selection of birthdays is independent. We assume from now on that birthdays are independent, so that the probability that i’s birthday5.4 Probabilistic analysis and further uses of indicator random variables 131 and j ’s birthday both fall on day r is Pr fbi D r and bj D rg D Pr fbi D rg Pr fbj D rg D 1=n2 : Thus, the probability that they both fall on the same day is Pr fbi D bj g D nX rD1 Pr fbi D r and bj D rg D nX rD1 .1=n2/ D 1=n : (5.6) More intuitively, once bi is chosen, the probability that bj is chosen to be the same day is 1=n. Thus, the probability that i and j have the same birthday is the same as the probability that the birthday of one of them falls on a given day. Notice, however, that this coincidence depends on the assumption that the birthdays are independent. We can analyze the probability of at least 2 out of k people having matching birthdays by looking at the complementary event. The probability that at least two of the birthdays match is 1 minus the probability that all the birthdays are different. The event that k people have distinct birthdays is Bk D k\ iD1 Ai ; where Ai is the event that person i’s birthday is different from person j ’s for all j bestscore 4 bestscore D score.i/ 5 for i D k C 1 to n 6 if score.i/ > bestscore 7 return i 8 return n We wish to determine, for each possible value of k, the probability that we hire the most qualiﬁed applicant. We then choose the best possible k,and implement the strategy with that value. For the moment, assume that k is ﬁxed. Let M.j/ D max1ij fscore.i/g denote the maximum score among ap- plicants 1 through j .LetS be the event that we succeed in choosing the best- qualiﬁed applicant, and let Si be the event that we succeed when the best-qualiﬁed applicant is the ith one interviewed. Since the various Si are disjoint, we have that Pr fSg D Pn iD1 Pr fSi g. Noting that we never succeed when the best-qualiﬁed applicant is one of the ﬁrst k,wehavethatPrfSi g D 0 for i D 1;2;:::;k. Thus, we obtain Pr fSg D nX iDkC1 Pr fSi g : (5.12) We now compute Pr fSi g. In order to succeed when the best-qualiﬁed applicant is the ith one, two things must happen. First, the best-qualiﬁed applicant must be in position i, an event which we denote by Bi . Second, the algorithm must not select any of the applicants in positions k C1 through i 1, which happens only if, for each j such that k C1 j i 1,weﬁndthatscore.j / < bestscore in line 6. (Because scores are unique, we can ignore the possibility of score.j / D bestscore.) In other words, all of the values score.k C 1/ through score.i 1/ must be less than M.k/; if any are greater than M.k/, we instead return the index of the ﬁrst one that is greater. We use Oi to denote the event that none of the applicants in position k C 1 through i 1 are chosen. Fortunately, the two events Bi and Oi are independent. The event Oi depends only on the relative ordering of the values in positions 1 through i 1, whereas Bi depends only on whether the value in position i is greater than the values in all other positions. The ordering of the values in positions 1 through i 1 does not affect whether the value in position i is greater than all of them, and the value in position i does not affect the ordering of the values in positions 1 through i 1. Thus we can apply equation (C.15) to obtain5.4 Probabilistic analysis and further uses of indicator random variables 141 Pr fSi g D Pr fBi \ Oi g D Pr fBi g Pr fOi g : The probability Pr fBi g is clearly 1=n, since the maximum is equally likely to be in any one of the n positions. For event Oi to occur, the maximum value in positions 1 through i1, which is equally likely to be in any of these i1 positions, must be in one of the ﬁrst k positions. Consequently, Pr fOi g D k=.i 1/ and Pr fSi g D k=.n.i 1//. Using equation (5.12), we have Pr fSg D nX iDkC1 Pr fSi g D nX iDkC1 k n.i 1/ D k n nX iDkC1 1 i 1 D k n n1X iDk 1 i : We approximate by integrals to bound this summation from above and below. By the inequalities (A.12), we have Z n k 1 x dx n1X iDk 1 i Z n1 k1 1 x dx : Evaluating these deﬁnite integrals gives us the bounds k n.ln n ln k/ Pr fSg k n.ln.n 1/ ln.k 1// ; which provide a rather tight bound for Pr fSg. Because we wish to maximize our probability of success, let us focus on choosing the value of k that maximizes the lower bound on Pr fSg. (Besides, the lower-bound expression is easier to maximize than the upper-bound expression.) Differentiating the expression .k=n/.ln nln k/ with respect to k, we obtain 1 n.ln n ln k 1/ : Setting this derivative equal to 0, we see that we maximize the lower bound on the probability when ln k D ln n1 D ln.n=e/ or, equivalently, when k D n=e. Thus, if we implement our strategy with k D n=e, we succeed in hiring our best-qualiﬁed applicant with probability at least 1=e.142 Chapter 5 Probabilistic Analysis and Randomized Algorithms Exercises 5.4-1 How many people must there be in a room before the probability that someone has the same birthday as you do is at least 1=2? How many people must there be before the probability that at least two people have a birthday on July 4 is greater than 1=2? 5.4-2 Suppose that we toss balls into b bins until some bin contains two balls. Each toss is independent, and each ball is equally likely to end up in any bin. What is the expected number of ball tosses? 5.4-3 ? For the analysis of the birthday paradox, is it important that the birthdays be mutu- ally independent, or is pairwise independence sufﬁcient? Justify your answer. 5.4-4 ? How many people should be invited to a party in order to make it likely that there are three people with the same birthday? 5.4-5 ? What is the probability that a k-string over a set of size n forms a k-permutation? How does this question relate to the birthday paradox? 5.4-6 ? Suppose that n balls are tossed into n bins, where each toss is independent and the ball is equally likely to end up in any bin. What is the expected number of empty bins? What is the expected number of bins with exactly one ball? 5.4-7 ? Sharpen the lower bound on streak length by showing that in n ﬂips of a fair coin, the probability is less than 1=n that no streak longer than lg n2 lg lg n consecutive heads occurs.Problems for Chapter 5 143 Problems 5-1 Probabilistic counting With a b-bit counter, we can ordinarily only count up to 2b 1. With R. Morris’s probabilistic counting, we can count up to a much larger value at the expense of some loss of precision. We let a counter value of i represent a count of ni for i D 0; 1; : : : ; 2b 1,where the ni form an increasing sequence of nonnegative values. We assume that the ini- tial value of the counter is 0, representing a count of n0 D 0.TheINCREMENT operation works on a counter containing the value i in a probabilistic manner. If i D 2b 1, then the operation reports an overﬂow error. Otherwise, the INCRE- MENT operation increases the counter by 1 with probability 1=.niC1 ni /,andit leaves the counter unchanged with probability 1 1=.niC1 ni /. If we select ni D i for all i 0, then the counter is an ordinary one. More interesting situations arise if we select, say, ni D 2i1 for i>0or ni D Fi (the ith Fibonacci number—see Section 3.2). For this problem, assume that n2b1 is large enough that the probability of an overﬂow error is negligible. a. Show that the expected value represented by the counter after n INCREMENT operations have been performed is exactly n. b. The analysis of the variance of the count represented by the counter depends on the sequence of the ni . Let us consider a simple case: ni D 100i for all i 0. Estimate the variance in the value represented by the register after n INCREMENT operations have been performed. 5-2 Searching an unsorted array This problem examines three algorithms for searching for a value x in an unsorted array A consisting of n elements. Consider the following randomized strategy: pick a random index i into A.If AŒi D x, then we terminate; otherwise, we continue the search by picking a new random index into A. We continue picking random indices into A until we ﬁnd an index j such that AŒj D x or until we have checked every element of A.Note that we pick from the whole set of indices each time, so that we may examine a given element more than once. a. Write pseudocode for a procedure RANDOM-SEARCH to implement the strat- egy above. Be sure that your algorithm terminates when all indices into A have been picked.144 Chapter 5 Probabilistic Analysis and Randomized Algorithms b. Suppose that there is exactly one index i such that AŒi D x. What is the expected number of indices into A that we must pick before we ﬁnd x and RANDOM-SEARCH terminates? c. Generalizing your solution to part (b), suppose that there are k 1 indices i such that AŒi D x. What is the expected number of indices into A that we must pick before we ﬁnd x and RANDOM-SEARCH terminates? Your answer should be a function of n and k. d. Suppose that there are no indices i such that AŒi D x. What is the expected number of indices into A that we must pick before we have checked all elements of A and RANDOM-SEARCH terminates? Now consider a deterministic linear search algorithm, which we refer to as DETERMINISTIC-SEARCH. Speciﬁcally, the algorithm searches A for x in order, considering AŒ1;AŒ2;AŒ3;:::;AŒn until either it ﬁnds AŒi D x or it reaches the end of the array. Assume that all possible permutations of the input array are equally likely. e. Suppose that there is exactly one index i such that AŒi D x. What is the average-case running time of DETERMINISTIC-SEARCH? What is the worst- case running time of DETERMINISTIC-SEARCH? f. Generalizing your solution to part (e), suppose that there are k 1 indices i such that AŒi D x. What is the average-case running time of DETERMINISTIC- SEARCH? What is the worst-case running time of DETERMINISTIC-SEARCH? Your answer should be a function of n and k. g. Suppose that there are no indices i such that AŒi D x. What is the average-case running time of DETERMINISTIC-SEARCH? What is the worst-case running time of DETERMINISTIC-SEARCH? Finally, consider a randomized algorithm SCRAMBLE-SEARCH that works by ﬁrst randomly permuting the input array and then running the deterministic lin- ear search given above on the resulting permuted array. h. Letting k be the number of indices i such that AŒi D x, give the worst-case and expected running times of SCRAMBLE-SEARCH for the cases in which k D 0 and k D 1. Generalize your solution to handle the case in which k 1. i. Which of the three searching algorithms would you use? Explain your answer.Notes for Chapter 5 145 Chapter notes Bollob´as [53], Hofri [174], and Spencer [321] contain a wealth of advanced prob- abilistic techniques. The advantages of randomized algorithms are discussed and surveyed by Karp [200] and Rabin [288]. The textbook by Motwani and Raghavan [262] gives an extensive treatment of randomized algorithms. Several variants of the hiring problem have been widely studied. These problems are more commonly referred to as “secretary problems.” An example of work in this area is the paper by Ajtai, Meggido, and Waarts [11].II Sorting and Order StatisticsIntroduction This part presents several algorithms that solve the following sorting problem: Input: A sequence of n numbers ha1;a2;:::;ani. Output: A permutation (reordering) ha0 1;a0 2;:::;a0 ni of the input sequence such that a0 1 a0 2 a0 n. The input sequence is usually an n-element array, although it may be represented in some other fashion, such as a linked list. The structure of the data In practice, the numbers to be sorted are rarely isolated values. Each is usually part of a collection of data called a record. Each record contains a key, which is the value to be sorted. The remainder of the record consists of satellite data, which are usually carried around with the key. In practice, when a sorting algorithm permutes the keys, it must permute the satellite data as well. If each record includes a large amount of satellite data, we often permute an array of pointers to the records rather than the records themselves in order to minimize data movement. In a sense, it is these implementation details that distinguish an algorithm from a full-blown program. A sorting algorithm describes the method by which we determine the sorted order, regardless of whether we are sorting individual numbers or large records containing many bytes of satellite data. Thus, when focusing on the problem of sorting, we typically assume that the input consists only of numbers. Translating an algorithm for sorting numbers into a program for sorting records148 Part II Sorting and Order Statistics is conceptually straightforward, although in a given engineering situation other subtleties may make the actual programming task a challenge. Why sorting? Many computer scientists consider sorting to be the most fundamental problem in the study of algorithms. There are several reasons: Sometimes an application inherently needs to sort information. For example, in order to prepare customer statements, banks need to sort checks by check number. Algorithms often use sorting as a key subroutine. For example, a program that renders graphical objects which are layered on top of each other might have to sort the objects according to an “above” relation so that it can draw these objects from bottom to top. We shall see numerous algorithms in this text that use sorting as a subroutine. We can draw from among a wide variety of sorting algorithms, and they em- ploy a rich set of techniques. In fact, many important techniques used through- out algorithm design appear in the body of sorting algorithms that have been developed over the years. In this way, sorting is also a problem of historical interest. We can prove a nontrivial lower bound for sorting (as we shall do in Chapter 8). Our best upper bounds match the lower bound asymptotically, and so we know that our sorting algorithms are asymptotically optimal. Moreover, we can use the lower bound for sorting to prove lower bounds for certain other problems. Many engineering issues come to the fore when implementing sorting algo- rithms. The fastest sorting program for a particular situation may depend on many factors, such as prior knowledge about the keys and satellite data, the memory hierarchy (caches and virtual memory) of the host computer, and the software environment. Many of these issues are best dealt with at the algorith- mic level, rather than by “tweaking” the code. Sorting algorithms We introduced two algorithms that sort n real numbers in Chapter 2. Insertion sort takes ‚.n2/ time in the worst case. Because its inner loops are tight, however, it is a fast in-place sorting algorithm for small input sizes. (Recall that a sorting algorithm sorts in place if only a constant number of elements of the input ar- ray are ever stored outside the array.) Merge sort has a better asymptotic running time, ‚.n lg n/,buttheMERGE procedure it uses does not operate in place.Part II Sorting and Order Statistics 149 In this part, we shall introduce two more algorithms that sort arbitrary real num- bers. Heapsort, presented in Chapter 6, sorts n numbers in place in O.nlg n/ time. It uses an important data structure, called a heap, with which we can also imple- ment a priority queue. Quicksort, in Chapter 7, also sorts n numbers in place, but its worst-case running time is ‚.n2/. Its expected running time is ‚.n lg n/, however, and it generally outperforms heapsort in practice. Like insertion sort, quicksort has tight code, and so the hidden constant factor in its running time is small. It is a popular algorithm for sorting large input arrays. Insertion sort, merge sort, heapsort, and quicksort are all comparison sorts: they determine the sorted order of an input array by comparing elements. Chapter 8 be- gins by introducing the decision-tree model in order to study the performance limi- tations of comparison sorts. Using this model, we prove a lower bound of .n lg n/ on the worst-case running time of any comparison sort on n inputs, thus showing that heapsort and merge sort are asymptotically optimal comparison sorts. Chapter 8 then goes on to show that we can beat this lower bound of .n lg n/ if we can gather information about the sorted order of the input by means other than comparing elements. The counting sort algorithm, for example, assumes that the input numbers are in the set f0; 1; : : : ; kg. By using array indexing as a tool for determining relative order, counting sort can sort n numbers in ‚.k C n/ time. Thus, when k D O.n/, counting sort runs in time that is linear in the size of the input array. A related algorithm, radix sort, can be used to extend the range of counting sort. If there are n integers to sort, each integer has d digits, and each digit can take on up to k possible values, then radix sort can sort the numbers in ‚.d.n C k// time. When d is a constant and k is O.n/, radix sort runs in linear time. A third algorithm, bucket sort, requires knowledge of the probabilistic distribution of numbers in the input array. It can sort n real numbers uniformly distributed in the half-open interval Œ0; 1/ in average-case O.n/ time. The following table summarizes the running times of the sorting algorithms from Chapters 2 and 6–8. As usual, n denotes the number of items to sort. For counting sort, the items to sort are integers in the set f0; 1; : : : ; kg. For radix sort, each item is a d-digit number, where each digit takes on k possible values. For bucket sort, we assume that the keys are real numbers uniformly distributed in the half-open interval Œ0; 1/. The rightmost column gives the average-case or expected running time, indicating which it gives when it differs from the worst-case running time. We omit the average-case running time of heapsort because we do not analyze it in this book.150 Part II Sorting and Order Statistics Worst-case Average-case/expected Algorithm running time running time Insertion sort ‚.n2/ ‚.n2/ Merge sort ‚.n lg n/ ‚.n lg n/ Heapsort O.nlg n/ — Quicksort ‚.n2/ ‚.n lg n/ (expected) Counting sort ‚.k C n/ ‚.k C n/ Radix sort ‚.d.n C k// ‚.d.n C k// Bucket sort ‚.n2/ ‚.n/ (average-case) Order statistics The ith order statistic of a set of n numbers is the ith smallest number in the set. We can, of course, select the ith order statistic by sorting the input and indexing the ith element of the output. With no assumptions about the input distribution, this method runs in .n lg n/ time, as the lower bound proved in Chapter 8 shows. In Chapter 9, we show that we can ﬁnd the ith smallest element in O.n/ time, even when the elements are arbitrary real numbers. We present a randomized algo- rithm with tight pseudocode that runs in ‚.n2/ time in the worst case, but whose expected running time is O.n/. We also give a more complicated algorithm that runs in O.n/ worst-case time. Background Although most of this part does not rely on difﬁcult mathematics, some sections do require mathematical sophistication. In particular, analyses of quicksort, bucket sort, and the order-statistic algorithm use probability, which is reviewed in Ap- pendix C, and the material on probabilistic analysis and randomized algorithms in Chapter 5. The analysis of the worst-case linear-time algorithm for order statis- tics involves somewhat more sophisticated mathematics than the other worst-case analyses in this part.6Heapsort In this chapter, we introduce another sorting algorithm: heapsort. Like merge sort, but unlike insertion sort, heapsort’s running time is O.nlg n/. Like insertion sort, but unlike merge sort, heapsort sorts in place: only a constant number of array elements are stored outside the input array at any time. Thus, heapsort combines the better attributes of the two sorting algorithms we have already discussed. Heapsort also introduces another algorithm design technique: using a data struc- ture, in this case one we call a “heap,” to manage information. Not only is the heap data structure useful for heapsort, but it also makes an efﬁcient priority queue. The heap data structure will reappear in algorithms in later chapters. The term “heap” was originally coined in the context of heapsort, but it has since come to refer to “garbage-collected storage,” such as the programming languages Java and Lisp provide. Our heap data structure is not garbage-collected storage, and whenever we refer to heaps in this book, we shall mean a data structure rather than an aspect of garbage collection. 6.1 Heaps The (binary) heap data structure is an array object that we can view as a nearly complete binary tree (see Section B.5.3), as shown in Figure 6.1. Each node of the tree corresponds to an element of the array. The tree is com- pletely ﬁlled on all levels except possibly the lowest, which is ﬁlled from the left up to a point. An array A that represents a heap is an object with two at- tributes: A:length, which (as usual) gives the number of elements in the array, and A:heap-size, which represents how many elements in the heap are stored within array A. That is, although AŒ1 : : A:length may contain numbers, only the ele- ments in AŒ1 : : A:heap-size,where0 A:heap-size A:length, are valid ele- ments of the heap. The root of the tree is AŒ1, and given the index i of a node, we can easily compute the indices of its parent, left child, and right child:152 Chapter 6 Heapsort (a) 1614108793241 12345678910 (b) 1 23 4567 8910 16 14 10 8793 241 Figure 6.1 A max-heap viewed as (a) abinarytreeand(b) an array. The number within the circle at each node in the tree is the value stored at that node. The number above a node is the corresponding index in the array. Above and below the array are lines showing parent-child relationships; parents are always to the left of their children. The tree has height three; the node at index 4 (with value 8) has height one. PARENT.i/ 1 return bi=2c LEFT.i/ 1 return 2i RIGHT.i/ 1 return 2i C 1 On most computers, the LEFT procedure can compute 2i in one instruction by simply shifting the binary representation of i left by one bit position. Similarly, the RIGHT procedure can quickly compute 2i C1 by shifting the binary representation of i left by one bit position and then adding in a 1 as the low-order bit. The PARENT procedure can compute bi=2c by shifting i right one bit position. Good implementations of heapsort often implement these procedures as “macros” or “in- line” procedures. There are two kinds of binary heaps: max-heaps and min-heaps. In both kinds, the values in the nodes satisfy a heap property, the speciﬁcs of which depend on the kind of heap. In a max-heap,themax-heap property is that for every node i other than the root, AŒPARENT.i/ AŒi ; that is, the value of a node is at most the value of its parent. Thus, the largest element in a max-heap is stored at the root, and the subtree rooted at a node contains6.1 Heaps 153 values no larger than that contained at the node itself. A min-heap is organized in the opposite way; the min-heap property is that for every node i other than the root, AŒPARENT.i/ AŒi : The smallest element in a min-heap is at the root. For the heapsort algorithm, we use max-heaps. Min-heaps commonly imple- ment priority queues, which we discuss in Section 6.5. We shall be precise in specifying whether we need a max-heap or a min-heap for any particular applica- tion, and when properties apply to either max-heaps or min-heaps, we just use the term “heap.” Viewing a heap as a tree, we deﬁne the height of a node in a heap to be the number of edges on the longest simple downward path from the node to a leaf, and we deﬁne the height of the heap to be the height of its root. Since a heap of n ele- ments is based on a complete binary tree, its height is ‚.lg n/ (see Exercise 6.1-2). We shall see that the basic operations on heaps run in time at most proportional to the height of the tree and thus take O.lg n/ time. The remainder of this chapter presents some basic procedures and shows how they are used in a sorting algorithm and a priority-queue data structure. The MAX-HEAPIFY procedure, which runs in O.lg n/ time, is the key to main- taining the max-heap property. The BUILD-MAX-HEAP procedure, which runs in linear time, produces a max- heap from an unordered input array. The HEAPSORT procedure, which runs in O.nlg n/ time, sorts an array in place. The MAX-HEAP-INSERT,HEAP-EXTRACT-MAX,HEAP-INCREASE-KEY, and HEAP-MAXIMUM procedures, which run in O.lg n/ time, allow the heap data structure to implement a priority queue. Exercises 6.1-1 What are the minimum and maximum numbers of elements in a heap of height h? 6.1-2 Show that an n-element heap has height blg nc. 6.1-3 Show that in any subtree of a max-heap, the root of the subtree contains the largest value occurring anywhere in that subtree.154 Chapter 6 Heapsort 6.1-4 Where in a max-heap might the smallest element reside, assuming that all elements are distinct? 6.1-5 Is an array that is in sorted order a min-heap? 6.1-6 Is the array with values h23; 17; 14; 6; 13; 10; 1; 5; 7; 12i a max-heap? 6.1-7 Show that, with the array representation for storing an n-element heap, the leaves are the nodes indexed by bn=2c C 1; bn=2c C 2;:::;n. 6.2 Maintaining the heap property In order to maintain the max-heap property, we call the procedure MAX-HEAPIFY. Its inputs are an array A andanindexi into the array. When it is called, MAX- HEAPIFY assumes that the binary trees rooted at LEFT.i/ and RIGHT.i/ are max- heaps, but that AŒi might be smaller than its children, thus violating the max-heap property. MAX-HEAPIFY lets the value at AŒi “ﬂoat down” in the max-heap so that the subtree rooted at index i obeys the max-heap property. MAX-HEAPIFY.A; i/ 1 l D LEFT.i/ 2 r D RIGHT.i/ 3 if l A:heap-size and AŒl > AŒi 4 largest D l 5 else largest D i 6 if r A:heap-size and AŒr > AŒlargest 7 largest D r 8 if largest ¤ i 9 exchange AŒi with AŒlargest 10 MAX-HEAPIFY.A; largest/ Figure 6.2 illustrates the action of MAX-HEAPIFY. At each step, the largest of the elements AŒi, AŒLEFT.i/,andAŒRIGHT.i/ is determined, and its index is stored in largest.IfAŒi is largest, then the subtree rooted at node i is already a max-heap and the procedure terminates. Otherwise, one of the two children has the largest element, and AŒi is swapped with AŒlargest, which causes node i and its6.2 Maintaining the heap property 155 16 410 14 7 9 281 (a) 16 14 10 4793 281 (b) 16 14 10 8793 241 (c) 3 1 3 4567 910 2 8 1 3 4567 910 2 8 1 3 4567 910 2 8 i i i Figure 6.2 The action of MAX-HEAPIFY.A; 2/,whereA:heap-size D 10. (a) The initial con- ﬁguration, with AŒ2 at node i D 2 violating the max-heap property since it is not larger than both children. The max-heap property is restored for node 2 in (b) by exchanging AŒ2 with AŒ4, which destroys the max-heap property for node 4. The recursive call MAX-HEAPIFY.A; 4/ now has i D 4. After swapping AŒ4 with AŒ9,asshownin(c), node 4 is ﬁxed up, and the recursive call MAX-HEAPIFY.A; 9/ yields no further change to the data structure. children to satisfy the max-heap property. The node indexed by largest,however, now has the original value AŒi, and thus the subtree rooted at largest might violate the max-heap property. Consequently, we call MAX-HEAPIFY recursively on that subtree. The running time of MAX-HEAPIFY on a subtree of size n rooted at a given node i is the ‚.1/ time to ﬁx up the relationships among the elements AŒi, AŒLEFT.i/,andAŒRIGHT.i/, plus the time to run MAX-HEAPIFY on a subtree rooted at one of the children of node i (assuming that the recursive call occurs). The children’s subtrees each have size at most 2n=3—the worst case occurs when the bottom level of the tree is exactly half full—and therefore we can describe the running time of MAX-HEAPIFY by the recurrence T .n/ T .2n=3/ C ‚.1/ :156 Chapter 6 Heapsort The solution to this recurrence, by case 2 of the master theorem (Theorem 4.1), is T .n/ D O.lg n/. Alternatively, we can characterize the running time of MAX- HEAPIFY on a node of height h as O.h/. Exercises 6.2-1 Using Figure 6.2 as a model, illustrate the operation of MAX-HEAPIFY.A; 3/ on the array A Dh27; 17; 3; 16; 13; 10; 1; 5; 7; 12; 4; 8; 9; 0i. 6.2-2 Starting with the procedure MAX-HEAPIFY, write pseudocode for the procedure MIN-HEAPIFY.A; i/, which performs the corresponding manipulation on a min- heap. How does the running time of MIN-HEAPIFY compare to that of MAX- HEAPIFY? 6.2-3 What is the effect of calling MAX-HEAPIFY.A; i/ when the element AŒi is larger than its children? 6.2-4 What is the effect of calling MAX-HEAPIFY.A; i/ for i>A:heap-size=2? 6.2-5 The code for MAX-HEAPIFY is quite efﬁcient in terms of constant factors, except possibly for the recursive call in line 10, which might cause some compilers to produce inefﬁcient code. Write an efﬁcient MAX-HEAPIFY that uses an iterative control construct (a loop) instead of recursion. 6.2-6 Show that the worst-case running time of MAX-HEAPIFY on a heap of size n is .lg n/.(Hint: For a heap with n nodes, give node values that cause MAX- HEAPIFY to be called recursively at every node on a simple path from the root down to a leaf.) 6.3 Building a heap We can use the procedure MAX-HEAPIFY in a bottom-up manner to convert an array AŒ1 : : n,wheren D A:length, into a max-heap. By Exercise 6.1-7, the elements in the subarray AŒ.bn=2cC1/::nare all leaves of the tree, and so each is6.3 Building a heap 157 a 1-element heap to begin with. The procedure BUILD-MAX-HEAP goes through the remaining nodes of the tree and runs MAX-HEAPIFY on each one. BUILD-MAX-HEAP.A/ 1 A:heap-size D A:length 2 for i D bA:length=2c downto 1 3MAX-HEAPIFY.A; i/ Figure 6.3 shows an example of the action of BUILD-MAX-HEAP. To show why BUILD-MAX-HEAP works correctly, we use the following loop invariant: At the start of each iteration of the for loop of lines 2–3, each node i C 1; i C 2;:::;nis the root of a max-heap. We need to show that this invariant is true prior to the ﬁrst loop iteration, that each iteration of the loop maintains the invariant, and that the invariant provides a useful property to show correctness when the loop terminates. Initialization: Prior to the ﬁrst iteration of the loop, i D bn=2c. Each node bn=2c C 1; bn=2c C 2;:::;nis a leaf and is thus the root of a trivial max-heap. Maintenance: To see that each iteration maintains the loop invariant, observe that the children of node i are numbered higher than i. By the loop invariant, there- fore, they are both roots of max-heaps. This is precisely the condition required for the call MAX-HEAPIFY.A; i/ to make node i a max-heap root. Moreover, the MAX-HEAPIFY call preserves the property that nodes i C 1; i C 2;:::;n are all roots of max-heaps. Decrementing i in the for loop update reestablishes the loop invariant for the next iteration. Termination: At termination, i D 0. By the loop invariant, each node 1;2;:::;n is the root of a max-heap. In particular, node 1 is. We can compute a simple upper bound on the running time of BUILD-MAX- HEAP as follows. Each call to MAX-HEAPIFY costs O.lg n/ time, and BUILD- MAX-HEAP makes O.n/ such calls. Thus, the running time is O.nlg n/.This upper bound, though correct, is not asymptotically tight. We can derive a tighter bound by observing that the time for MAX-HEAPIFY to run at a node varies with the height of the node in the tree, and the heights of most nodes are small. Our tighter analysis relies on the properties that an n-element heap has height blg nc (see Exercise 6.1-2) and at most ˙ n=2hC1 nodes of any height h (see Exercise 6.3-3). The time required by MAX-HEAPIFY when called on a node of height h is O.h/, and so we can express the total cost of BUILD-MAX-HEAP as being bounded from above by158 Chapter 6 Heapsort 1 23 4567 8910 1 23 4567 8910 1 23 4567 8910 1 23 4567 8910 1 23 4567 8910 1 23 4567 8910 4 13 2910 14 8 7 (a) 16 41 23 16 9 10 14 8 7 4 13 2910 14 8 7 (b) 16 4 13 14 9 10 287 (c) 16 4 110 14 9 3 287 (d) 16 4 16 10 14 9 3 281 (e) 7 16 14 10 893 241 (f) 7 A ii ii i Figure 6.3 The operation of BUILD-MAX-HEAP, showing the data structure before the call to MAX-HEAPIFY in line 3 of BUILD-MAX-HEAP. (a) A 10-element input array A and the bi- nary tree it represents. The ﬁgure shows that the loop index i refers to node 5 before the call MAX-HEAPIFY.A; i/. (b) The data structure that results. The loop index i for the next iteration refers to node 4. (c)–(e) Subsequent iterations of the for loop in BUILD-MAX-HEAP. Observe that whenever MAX-HEAPIFY is called on a node, the two subtrees of that node are both max-heaps. (f) The max-heap after BUILD-MAX-HEAP ﬁnishes.6.4 The heapsort algorithm 159 blg ncX hD0 l n 2hC1 m O.h/ D O n blg ncX hD0 h 2h ! : We evalaute the last summation by substituting x D 1=2 in the formula (A.8), yielding 1X hD0 h 2h D 1=2 .1 1=2/2 D 2: Thus, we can bound the running time of BUILD-MAX-HEAP as O n blg ncX hD0 h 2h ! D O n 1X hD0 h 2h ! D O.n/ : Hence, we can build a max-heap from an unordered array in linear time. We can build a min-heap by the procedure BUILD-MIN-HEAP, which is the same as BUILD-MAX-HEAP but with the call to MAX-HEAPIFY in line 3 replaced by a call to MIN-HEAPIFY (see Exercise 6.2-2). BUILD-MIN-HEAP produces a min-heap from an unordered linear array in linear time. Exercises 6.3-1 Using Figure 6.3 as a model, illustrate the operation of BUILD-MAX-HEAP on the array A Dh5; 3; 17; 10; 84; 19; 6; 22; 9i. 6.3-2 Why do we want the loop index i in line 2 of BUILD-MAX-HEAP to decrease from bA:length=2c to 1 rather than increase from 1 to bA:length=2c? 6.3-3 Show that there are at most ˙ n=2hC1 nodes of height h in any n-element heap. 6.4 The heapsort algorithm The heapsort algorithm starts by using BUILD-MAX-HEAP to build a max-heap on the input array AŒ1 : : n,wheren D A:length. Since the maximum element of the array is stored at the root AŒ1, we can put it into its correct ﬁnal position160 Chapter 6 Heapsort by exchanging it with AŒn. If we now discard node n from the heap—and we can do so by simply decrementing A:heap-size—we observe that the children of the root remain max-heaps, but the new root element might violate the max-heap property. All we need to do to restore the max-heap property, however, is call MAX-HEAPIFY.A; 1/, which leaves a max-heap in AŒ1 : : n 1. The heapsort algorithm then repeats this process for the max-heap of size n 1 down to a heap of size 2. (See Exercise 6.4-2 for a precise loop invariant.) HEAPSORT.A/ 1BUILD-MAX-HEAP.A/ 2 for i D A:length downto 2 3 exchange AŒ1 with AŒi 4 A:heap-size D A:heap-size 1 5MAX-HEAPIFY.A; 1/ Figure 6.4 shows an example of the operation of HEAPSORT after line 1 has built the initial max-heap. The ﬁgure shows the max-heap before the ﬁrst iteration of the for loop of lines 2–5 and after each iteration. The HEAPSORT procedure takes time O.nlg n/, since the call to BUILD-MAX- HEAP takes time O.n/ and each of the n 1 calls to MAX-HEAPIFY takes time O.lg n/. Exercises 6.4-1 Using Figure 6.4 as a model, illustrate the operation of HEAPSORT on the array A Dh5; 13; 2; 25; 7; 17; 20; 8; 4i. 6.4-2 Argue the correctness of HEAPSORT using the following loop invariant: At the start of each iteration of the for loop of lines 2–5, the subarray AŒ1 : : i is a max-heap containing the i smallest elements of AŒ1 : : n,and the subarray AŒi C 1::ncontains the n i largest elements of AŒ1 : : n, sorted. 6.4-3 What is the running time of HEAPSORT on an array A of length n that is already sorted in increasing order? What about decreasing order? 6.4-4 Show that the worst-case running time of HEAPSORT is .n lg n/.6.4 The heapsort algorithm 161 (a) (b) (c) (d) (e) (f) (g) (h) (i) (j) (k) 1234789101416 10 2 13 4789 1614 1 23 4789 161410 3 21 9874 10 14 16 4 23 9871 10 14 16 8 37 4219 161410 7 43 9821 10 14 16 9 83 2174 161410 10 89 3174 16142 14 810 3974 1612 16 14 10 3978 142 A i i i ii ii i i Figure 6.4 The operation of HEAPSORT. (a) The max-heap data structure just after BUILD-MAX- HEAP has built it in line 1. (b)–(j) The max-heap just after each call of MAX-HEAPIFY in line 5, showing the value of i at that time. Only lightly shaded nodes remain in the heap. (k) The resulting sorted array A.162 Chapter 6 Heapsort 6.4-5 ? Show that when all elements are distinct, the best-case running time of HEAPSORT is .n lg n/. 6.5 Priority queues Heapsort is an excellent algorithm, but a good implementation of quicksort, pre- sented in Chapter 7, usually beats it in practice. Nevertheless, the heap data struc- ture itself has many uses. In this section, we present one of the most popular ap- plications of a heap: as an efﬁcient priority queue. As with heaps, priority queues come in two forms: max-priority queues and min-priority queues. We will focus here on how to implement max-priority queues, which are in turn based on max- heaps; Exercise 6.5-3 asks you to write the procedures for min-priority queues. A priority queue is a data structure for maintaining a set S of elements, each with an associated value called a key.Amax-priority queue supports the following operations: INSERT.S; x/ inserts the element x into the set S, which is equivalent to the oper- ation S D S [ fxg. MAXIMUM.S/ returns the element of S with the largest key. EXTRACT-MAX.S/ removes and returns the element of S with the largest key. INCREASE-KEY.S;x;k/increases the value of element x’s key to the new value k, which is assumed to be at least as large as x’s current key value. Among their other applications, we can use max-priority queues to schedule jobs on a shared computer. The max-priority queue keeps track of the jobs to be performed and their relative priorities. When a job is ﬁnished or interrupted, the scheduler selects the highest-priority job from among those pending by calling EXTRACT-MAX. The scheduler can add a new job to the queue at any time by calling INSERT. Alternatively, a min-priority queue supports the operations INSERT,MINIMUM, EXTRACT-MIN,andDECREASE-KEY. A min-priority queue can be used in an event-driven simulator. The items in the queue are events to be simulated, each with an associated time of occurrence that serves as its key. The events must be simulated in order of their time of occurrence, because the simulation of an event can cause other events to be simulated in the future. The simulation program calls EXTRACT-MIN at each step to choose the next event to simulate. As new events are produced, the simulator inserts them into the min-priority queue by calling INSERT.6.5 Priority queues 163 We shall see other uses for min-priority queues, highlighting the DECREASE-KEY operation, in Chapters 23 and 24. Not surprisingly, we can use a heap to implement a priority queue. In a given ap- plication, such as job scheduling or event-driven simulation, elements of a priority queue correspond to objects in the application. We often need to determine which application object corresponds to a given priority-queue element, and vice versa. When we use a heap to implement a priority queue, therefore, we often need to store a handle to the corresponding application object in each heap element. The exact makeup of the handle (such as a pointer or an integer) depends on the ap- plication. Similarly, we need to store a handle to the corresponding heap element in each application object. Here, the handle would typically be an array index. Because heap elements change locations within the array during heap operations, an actual implementation, upon relocating a heap element, would also have to up- date the array index in the corresponding application object. Because the details of accessing application objects depend heavily on the application and its imple- mentation, we shall not pursue them here, other than noting that in practice, these handles do need to be correctly maintained. Now we discuss how to implement the operations of a max-priority queue. The procedure HEAP-MAXIMUM implements the MAXIMUM operation in ‚.1/ time. HEAP-MAXIMUM.A/ 1 return AŒ1 The procedure HEAP-EXTRACT-MAX implements the EXTRACT-MAX opera- tion. It is similar to the for loop body (lines 3–5) of the HEAPSORT procedure. HEAP-EXTRACT-MAX.A/ 1 if A:heap-size <1 2 error “heap underﬂow” 3 max D AŒ1 4 AŒ1 D AŒA:heap-size 5 A:heap-size D A:heap-size 1 6MAX-HEAPIFY.A; 1/ 7 return max The running time of HEAP-EXTRACT-MAX is O.lg n/, since it performs only a constant amount of work on top of the O.lg n/ time for MAX-HEAPIFY. The procedure HEAP-INCREASE-KEY implements the INCREASE-KEY opera- tion. An index i into the array identiﬁes the priority-queue element whose key we wish to increase. The procedure ﬁrst updates the key of element AŒi to its new value. Because increasing the key of AŒi might violate the max-heap property,164 Chapter 6 Heapsort the procedure then, in a manner reminiscent of the insertion loop (lines 5–7) of INSERTION-SORT from Section 2.1, traverses a simple path from this node toward the root to ﬁnd a proper place for the newly increased key. As HEAP-INCREASE- KEY traverses this path, it repeatedly compares an element to its parent, exchang- ing their keys and continuing if the element’s key is larger, and terminating if the el- ement’s key is smaller, since the max-heap property now holds. (See Exercise 6.5-5 for a precise loop invariant.) HEAP-INCREASE-KEY.A; i; key/ 1 if key < AŒi 2 error “new key is smaller than current key” 3 AŒi D key 4 while i>1and AŒPARENT.i/ < AŒi 5 exchange AŒi with AŒPARENT.i/ 6 i D PARENT.i/ Figure 6.5 shows an example of a HEAP-INCREASE-KEY operation. The running time of HEAP-INCREASE-KEY on an n-element heap is O.lg n/, since the path traced from the node updated in line 3 to the root has length O.lg n/. The procedure MAX-HEAP-INSERT implements the INSERT operation. It takes as an input the key of the new element to be inserted into max-heap A. The proce- dure ﬁrst expands the max-heap by adding to the tree a new leaf whose key is 1. Then it calls HEAP-INCREASE-KEY to set the key of this new node to its correct value and maintain the max-heap property. MAX-HEAP-INSERT.A; key/ 1 A:heap-size D A:heap-size C 1 2 AŒA:heap-size D1 3HEAP-INCREASE-KEY.A; A:heap-size; key/ The running time of MAX-HEAP-INSERT on an n-element heap is O.lg n/. In summary, a heap can support any priority-queue operation on a set of size n in O.lg n/ time. Exercises 6.5-1 Illustrate the operation of HEAP-EXTRACT-MAX on the heap A Dh15; 13; 9; 5; 12;8;7;4;0;6;2;1i.6.5 Priority queues 165 16 14 10 8793 241 (a) i 16 14 10 8793 2 15 1 (b) 16 14 10 8 79 3 2 15 1 (c) i i 16 14 10 8 79 3 2 15 1 (d) i Figure 6.5 The operation of HEAP-INCREASE-KEY. (a) The max-heap of Figure 6.4(a) with a node whose index is i heavily shaded. (b) This node has its key increased to 15. (c) After one iteration of the while loop of lines 4–6, the node and its parent have exchanged keys, and the index i moves up to the parent. (d) The max-heap after one more iteration of the while loop. At this point, AŒPARENT.i/ AŒi. The max-heap property now holds and the procedure terminates. 6.5-2 Illustrate the operation of MAX-HEAP-INSERT.A; 10/ on the heap A Dh15; 13; 9; 5;12;8;7;4;0;6;2;1i. 6.5-3 Write pseudocode for the procedures HEAP-MINIMUM,HEAP-EXTRACT-MIN, HEAP-DECREASE-KEY,andMIN-HEAP-INSERT that implement a min-priority queue with a min-heap. 6.5-4 Why do we bother setting the key of the inserted node to 1 in line 2 of MAX- HEAP-INSERT when the next thing we do is increase its key to the desired value?166 Chapter 6 Heapsort 6.5-5 Argue the correctness of HEAP-INCREASE-KEY using the following loop invari- ant: At the start of each iteration of the while loop of lines 4–6, the subarray AŒ1 : : A:heap-size satisﬁes the max-heap property, except that there may be one violation: AŒi may be larger than AŒPARENT.i/. You may assume that the subarray AŒ1 : : A:heap-size satisﬁes the max-heap prop- erty at the time HEAP-INCREASE-KEY is called. 6.5-6 Each exchange operation on line 5 of HEAP-INCREASE-KEY typically requires three assignments. Show how to use the idea of the inner loop of INSERTION- SORT to reduce the three assignments down to just one assignment. 6.5-7 Show how to implement a ﬁrst-in, ﬁrst-out queue with a priority queue. Show how to implement a stack with a priority queue. (Queues and stacks are deﬁned in Section 10.1.) 6.5-8 The operation HEAP-DELETE.A; i/ deletes the item in node i from heap A.Give an implementation of HEAP-DELETE that runs in O.lg n/ time for an n-element max-heap. 6.5-9 Give an O.nlg k/-time algorithm to merge k sorted lists into one sorted list, where n is the total number of elements in all the input lists. (Hint: Use a min- heap for k-way merging.) Problems 6-1 Building a heap using insertion We can build a heap by repeatedly calling MAX-HEAP-INSERT to insert the ele- ments into the heap. Consider the following variation on the BUILD-MAX-HEAP procedure:Problems for Chapter 6 167 BUILD-MAX-HEAP0 .A/ 1 A:heap-size D 1 2 for i D 2 to A:length 3MAX-HEAP-INSERT.A; AŒi/ a. Do the procedures BUILD-MAX-HEAP and BUILD-MAX-HEAP0 always create the same heap when run on the same input array? Prove that they do, or provide a counterexample. b. Show that in the worst case, BUILD-MAX-HEAP0 requires ‚.n lg n/ time to build an n-element heap. 6-2 Analysis of d-ary heaps A d-ary heap is like a binary heap, but (with one possible exception) non-leaf nodes have d children instead of 2 children. a. How would you represent a d-ary heap in an array? b. What is the height of a d-ary heap of n elements in terms of n and d? c. Give an efﬁcient implementation of EXTRACT-MAX in a d-ary max-heap. An- alyze its running time in terms of d and n. d. Give an efﬁcient implementation of INSERT in a d-ary max-heap. Analyze its running time in terms of d and n. e. Give an efﬁcient implementation of INCREASE-KEY.A;i;k/, which ﬂags an error if k < AŒi, but otherwise sets AŒi D k and then updates the d-ary max- heap structure appropriately. Analyze its running time in terms of d and n. 6-3 Young tableaus An m n Young tableau is an m n matrix such that the entries of each row are in sorted order from left to right and the entries of each column are in sorted order from top to bottom. Some of the entries of a Young tableau may be 1,whichwe treat as nonexistent elements. Thus, a Young tableau can be used to hold r mn ﬁnite numbers. a. Draw a 44 Young tableau containing the elements f9; 16; 3; 2; 4; 8; 5; 14; 12g. b. Argue that an m n Young tableau Y is empty if Y Œ1; 1 D1. Argue that Y is full (contains mn elements) if YŒm;n<1.168 Chapter 6 Heapsort c. Give an algorithm to implement EXTRACT-MIN on a nonempty m n Young tableau that runs in O.m C n/ time. Your algorithm should use a recur- sive subroutine that solves an m n problem by recursively solving either an .m 1/ n or an m .n 1/ subproblem. (Hint: Think about MAX- HEAPIFY.) Deﬁne T.p/,wherep D m C n, to be the maximum running time of EXTRACT-MIN on any m n Young tableau. Give and solve a recurrence for T.p/that yields the O.m C n/ time bound. d. Show how to insert a new element into a nonfull m n Young tableau in O.m C n/ time. e. Using no other sorting method as a subroutine, show how to use an nn Young tableau to sort n2 numbers in O.n3/ time. f. Give an O.m C n/-time algorithm to determine whether a given number is stored in a given m n Young tableau. Chapter notes The heapsort algorithm was invented by Williams [357], who also described how to implement a priority queue with a heap. The BUILD-MAX-HEAP procedure was suggested by Floyd [106]. We use min-heaps to implement min-priority queues in Chapters 16, 23, and 24. We also give an implementation with improved time bounds for certain operations in Chapter 19 and, assuming that the keys are drawn from a bounded set of non- negative integers, Chapter 20. If the data are b-bit integers, and the computer memory consists of addressable b-bit words, Fredman and Willard [115] showed how to implement MINIMUM in O.1/ time and INSERT and EXTRACT-MIN in O. p lg n/ time. Thorup [337] has improved the O. p lg n/ bound to O.lg lg n/ time. This bound uses an amount of space unbounded in n, but it can be implemented in linear space by using random- ized hashing. An important special case of priority queues occurs when the sequence of EXTRACT-MIN operations is monotone, that is, the values returned by succes- sive EXTRACT-MIN operations are monotonically increasing over time. This case arises in several important applications, such as Dijkstra’s single-source shortest- paths algorithm, which we discuss in Chapter 24, and in discrete-event simula- tion. For Dijkstra’s algorithm it is particularly important that the DECREASE-KEY operation be implemented efﬁciently. For the monotone case, if the data are in- tegers in the range 1;2;:::;C, Ahuja, Mehlhorn, Orlin, and Tarjan [8] describeNotes for Chapter 6 169 how to implement EXTRACT-MIN and INSERT in O.lg C/ amortized time (see Chapter 17 for more on amortized analysis) and DECREASE-KEY in O.1/ time, using a data structure called a radix heap. The O.lg C/ bound can be improved to O. p lg C/ using Fibonacci heaps (see Chapter 19) in conjunction with radix heaps. Cherkassky, Goldberg, and Silverstein [65] further improved the bound to O.lg1=3C C/ expected time by combining the multilevel bucketing structure of Denardo and Fox [85] with the heap of Thorup mentioned earlier. Raman [291] further improved these results to obtain a bound of O.min.lg1=4C C;lg1=3C n//, for any ﬁxed >0.7 Quicksort The quicksort algorithm has a worst-case running time of ‚.n2/ on an input array of n numbers. Despite this slow worst-case running time, quicksort is often the best practical choice for sorting because it is remarkably efﬁcient on the average: its expected running time is ‚.n lg n/, and the constant factors hidden in the ‚.n lg n/ notation are quite small. It also has the advantage of sorting in place (see page 17), and it works well even in virtual-memory environments. Section 7.1 describes the algorithm and an important subroutine used by quick- sort for partitioning. Because the behavior of quicksort is complex, we start with an intuitive discussion of its performance in Section 7.2 and postpone its precise analysis to the end of the chapter. Section 7.3 presents a version of quicksort that uses random sampling. This algorithm has a good expected running time, and no particular input elicits its worst-case behavior. Section 7.4 analyzes the random- ized algorithm, showing that it runs in ‚.n2/ time in the worst case and, assuming distinct elements, in expected O.nlg n/ time. 7.1 Description of quicksort Quicksort, like merge sort, applies the divide-and-conquer paradigm introduced in Section 2.3.1. Here is the three-step divide-and-conquer process for sorting a typical subarray AŒp : : r: Divide: Partition (rearrange) the array AŒp : : r into two (possibly empty) subar- rays AŒp : : q 1 and AŒq C 1::rsuch that each element of AŒp : : q 1 is less than or equal to AŒq, which is, in turn, less than or equal to each element of AŒq C 1::r. Compute the index q as part of this partitioning procedure. Conquer: Sort the two subarrays AŒp : : q 1 and AŒq C1::rby recursive calls to quicksort.7.1 Description of quicksort 171 Combine: Because the subarrays are already sorted, no work is needed to combine them: the entire array AŒp : : r is now sorted. The following procedure implements quicksort: QUICKSORT.A;p;r/ 1 if p x. 3. If k D r,thenAŒk D x.172 Chapter 7 Quicksort 28713564 p,j ri (a) 28713564 p,i rj (b) 28713564 p,i rj (c) 28713564 p,i rj (d) 2871 3564 prj (e) i 28713 564 prj (f) i 28713 564 prj (g) i 28713 564 pr (h) i 28713 564 pr (i) i Figure 7.1 The operation of PARTITION on a sample array. Array entry AŒr becomes the pivot element x. Lightly shaded array elements are all in the ﬁrst partition with values no greater than x. Heavily shaded elements are in the second partition with values greater than x. The unshaded el- ements have not yet been put in one of the ﬁrst two partitions, and the ﬁnal white element is the pivot x. (a) The initial array and variable settings. None of the elements have been placed in either of the ﬁrst two partitions. (b) The value 2 is “swapped with itself” and put in the partition of smaller values. (c)–(d) The values 8 and 7 are added to the partition of larger values. (e) The values 1 and 8 are swapped, and the smaller partition grows. (f) The values 3 and 7 are swapped, and the smaller partition grows. (g)–(h) The larger partition grows to include 5 and 6, and the loop terminates. (i) In lines 7–8, the pivot element is swapped so that it lies between the two partitions. The indices between j and r 1 are not covered by any of the three cases, and the values in these entries have no particular relationship to the pivot x. We need to show that this loop invariant is true prior to the ﬁrst iteration, that each iteration of the loop maintains the invariant, and that the invariant provides a useful property to show correctness when the loop terminates.7.1 Description of quicksort 173 ≤ x > x unrestricted x pi j r Figure 7.2 The four regions maintained by the procedure PARTITION on a subarray AŒp : : r.The values in AŒp : : i are all less than or equal to x,thevaluesinAŒi C 1::j 1 are all greater than x, and AŒr D x. The subarray AŒj::r 1 can take on any values. Initialization: Prior to the ﬁrst iteration of the loop, i D p 1 and j D p.Be- cause no values lie between p and i and no values lie between i C 1 and j 1, the ﬁrst two conditions of the loop invariant are trivially satisﬁed. The assign- ment in line 1 satisﬁes the third condition. Maintenance: As Figure 7.3 shows, we consider two cases, depending on the outcome of the test in line 4. Figure 7.3(a) shows what happens when AŒj > x; the only action in the loop is to increment j . After j is incremented, condition 2 holds for AŒj 1 and all other entries remain unchanged. Figure 7.3(b) shows what happens when AŒj x; the loop increments i,swapsAŒi and AŒj , and then increments j . Because of the swap, we now have that AŒi x,and condition 1 is satisﬁed. Similarly, we also have that AŒj 1 > x, since the item that was swapped into AŒj 1 is, by the loop invariant, greater than x. Termination: At termination, j D r. Therefore, every entry in the array is in one of the three sets described by the invariant, and we have partitioned the values in the array into three sets: those less than or equal to x, those greater than x, and a singleton set containing x. The ﬁnal two lines of PARTITION ﬁnish up by swapping the pivot element with the leftmost element greater than x, thereby moving the pivot into its correct place in the partitioned array, and then returning the pivot’s new index. The output of PARTITION now satisﬁes the speciﬁcations given for the divide step. In fact, it satisﬁes a slightly stronger condition: after line 2 of QUICKSORT, AŒq is strictly less than every element of AŒq C 1::r. The running time of PARTITION on the subarray AŒp : : r is ‚.n/,where n D r p C 1 (see Exercise 7.1-3). Exercises 7.1-1 Using Figure 7.1 as a model, illustrate the operation of PARTITION on the array A Dh13; 19; 9; 5; 12; 8; 7; 4; 21; 2; 6; 11i.174 Chapter 7 Quicksort ≤ x > x x pi j r >x(a) ≤ x > x x pi j r ≤ x > x x pi j r ≤ x(b) ≤ x > x x pi jr Figure 7.3 The two cases for one iteration of procedure PARTITION. (a) If AŒj > x, the only action is to increment j, which maintains the loop invariant. (b) If AŒj x, index i is incremented, AŒi and AŒj are swapped, and then j is incremented. Again, the loop invariant is maintained. 7.1-2 What value of q does PARTITION return when all elements in the array AŒp : : r have the same value? Modify PARTITION so that q D b.p C r/=2c when all elements in the array AŒp : : r have the same value. 7.1-3 Give a brief argument that the running time of PARTITION on a subarray of size n is ‚.n/. 7.1-4 How would you modify QUICKSORT to sort into nonincreasing order? 7.2 Performance of quicksort The running time of quicksort depends on whether the partitioning is balanced or unbalanced, which in turn depends on which elements are used for partitioning. If the partitioning is balanced, the algorithm runs asymptotically as fast as merge7.2 Performance of quicksort 175 sort. If the partitioning is unbalanced, however, it can run asymptotically as slowly as insertion sort. In this section, we shall informally investigate how quicksort performs under the assumptions of balanced versus unbalanced partitioning. Worst-case partitioning The worst-case behavior for quicksort occurs when the partitioning routine pro- duces one subproblem with n 1 elements and one with 0 elements. (We prove this claim in Section 7.4.1.) Let us assume that this unbalanced partitioning arises in each recursive call. The partitioning costs ‚.n/ time. Since the recursive call on an array of size 0 just returns, T.0/D ‚.1/, and the recurrence for the running time is T .n/ D T.n 1/ C T.0/C ‚.n/ D T.n 1/ C ‚.n/ : Intuitively, if we sum the costs incurred at each level of the recursion, we get an arithmetic series (equation (A.2)), which evaluates to ‚.n2/. Indeed, it is straightforward to use the substitution method to prove that the recurrence T .n/ D T.n 1/ C ‚.n/ has the solution T .n/ D ‚.n2/. (See Exercise 7.2-1.) Thus, if the partitioning is maximally unbalanced at every recursive level of the algorithm, the running time is ‚.n2/. Therefore the worst-case running time of quicksort is no better than that of insertion sort. Moreover, the ‚.n2/ running time occurs when the input array is already completely sorted—a common situation in which insertion sort runs in O.n/ time. Best-case partitioning In the most even possible split, PARTITION produces two subproblems, each of size no more than n=2, since one is of size bn=2c and one of size dn=2e1.Inthis case, quicksort runs much faster. The recurrence for the running time is then T .n/ D 2T .n=2/ C ‚.n/ ; where we tolerate the sloppiness from ignoring the ﬂoor and ceiling and from sub- tracting 1. By case 2 of the master theorem (Theorem 4.1), this recurrence has the solution T .n/ D ‚.n lg n/. By equally balancing the two sides of the partition at every level of the recursion, we get an asymptotically faster algorithm. Balanced partitioning The average-case running time of quicksort is much closer to the best case than to the worst case, as the analyses in Section 7.4 will show. The key to understand-176 Chapter 7 Quicksort n cn cn cn cn cn cn 1 1 O.nlg n/ log10 n log10=9 n 1 10 n 9 10 n 1 100 n 9 100 n9 100 n 81 100 n 81 1000 n 729 1000 n Figure 7.4 A recursion tree for QUICKSORT in which PARTITION always produces a 9-to-1 split, yielding a running time of O.nlg n/. Nodes show subproblem sizes, with per-level costs on the right. The per-level costs include the constant c implicit in the ‚.n/ term. ing why is to understand how the balance of the partitioning is reﬂected in the recurrence that describes the running time. Suppose, for example, that the partitioning algorithm always produces a 9-to-1 proportional split, which at ﬁrst blush seems quite unbalanced. We then obtain the recurrence T .n/ D T .9n=10/ C T .n=10/ C cn ; on the running time of quicksort, where we have explicitly included the constant c hidden in the ‚.n/ term. Figure 7.4 shows the recursion tree for this recurrence. Notice that every level of the tree has cost cn, until the recursion reaches a bound- ary condition at depth log10 n D ‚.lg n/, and then the levels have cost at most cn. The recursion terminates at depth log10=9 n D ‚.lg n/. The total cost of quick- sort is therefore O.nlg n/. Thus, with a 9-to-1 proportional split at every level of recursion, which intuitively seems quite unbalanced, quicksort runs in O.nlg n/ time—asymptotically the same as if the split were right down the middle. Indeed, even a 99-to-1 split yields an O.nlg n/ running time. In fact, any split of constant proportionality yields a recursion tree of depth ‚.lg n/, where the cost at each level is O.n/. The running time is therefore O.nlg n/ whenever the split has constant proportionality.7.2 Performance of quicksort 177 n 0 n–1 (n–1)/2 – 1 (n–1)/2 n (n–1)/2 (a) (b) (n–1)/2 Θ(n) Θ(n) Figure 7.5 (a) Two levels of a recursion tree for quicksort. The partitioning at the root costs n and produces a “bad” split: two subarrays of sizes 0 and n 1. The partitioning of the subarray of size n 1 costs n 1 and produces a “good” split: subarrays of size .n 1/=2 1 and .n 1/=2. (b) A single level of a recursion tree that is very well balanced. In both parts, the partitioning cost for the subproblems shown with elliptical shading is ‚.n/. Yet the subproblems remaining to be solved in (a), shown with square shading, are no larger than the corresponding subproblems remaining to be solved in (b). Intuition for the average case To develop a clear notion of the randomized behavior of quicksort, we must make an assumption about how frequently we expect to encounter the various inputs. The behavior of quicksort depends on the relative ordering of the values in the array elements given as the input, and not by the particular values in the array. As in our probabilistic analysis of the hiring problem in Section 5.2, we will assume for now that all permutations of the input numbers are equally likely. When we run quicksort on a random input array, the partitioning is highly un- likely to happen in the same way at every level, as our informal analysis has as- sumed. We expect that some of the splits will be reasonably well balanced and that some will be fairly unbalanced. For example, Exercise 7.2-6 asks you to show that about 80 percent of the time PARTITION produces a split that is more balanced than 9 to 1, and about 20 percent of the time it produces a split that is less balanced than 9 to 1. In the average case, PARTITION produces a mix of “good” and “bad” splits. In a recursion tree for an average-case execution of PARTITION, the good and bad splits are distributed randomly throughout the tree. Suppose, for the sake of intuition, that the good and bad splits alternate levels in the tree, and that the good splits are best-case splits and the bad splits are worst-case splits. Figure 7.5(a) shows the splits at two consecutive levels in the recursion tree. At the root of the tree, the cost is n for partitioning, and the subarrays produced have sizes n 1 and 0: the worst case. At the next level, the subarray of size n 1 undergoes best-case partitioning into subarrays of size .n 1/=2 1 and .n 1/=2. Let’s assume that the boundary-condition cost is 1 for the subarray of size 0.178 Chapter 7 Quicksort The combination of the bad split followed by the good split produces three sub- arrays of sizes 0, .n 1/=2 1,and.n 1/=2 at a combined partitioning cost of ‚.n/ C ‚.n 1/ D ‚.n/. Certainly, this situation is no worse than that in Figure 7.5(b), namely a single level of partitioning that produces two subarrays of size .n 1/=2, at a cost of ‚.n/. Yet this latter situation is balanced! Intuitively, the ‚.n 1/ cost of the bad split can be absorbed into the ‚.n/ cost of the good split, and the resulting split is good. Thus, the running time of quicksort, when lev- els alternate between good and bad splits, is like the running time for good splits alone: still O.nlg n/, but with a slightly larger constant hidden by the O-notation. We shall give a rigorous analysis of the expected running time of a randomized version of quicksort in Section 7.4.2. Exercises 7.2-1 Use the substitution method to prove that the recurrence T .n/ D T.n 1/ C ‚.n/ has the solution T .n/ D ‚.n2/, as claimed at the beginning of Section 7.2. 7.2-2 What is the running time of QUICKSORT when all elements of array A have the same value? 7.2-3 Show that the running time of QUICKSORT is ‚.n2/ when the array A contains distinct elements and is sorted in decreasing order. 7.2-4 Banks often record transactions on an account in order of the times of the transac- tions, but many people like to receive their bank statements with checks listed in order by check number. People usually write checks in order by check number, and merchants usually cash them with reasonable dispatch. The problem of converting time-of-transaction ordering to check-number ordering is therefore the problem of sorting almost-sorted input. Argue that the procedure INSERTION-SORT would tend to beat the procedure QUICKSORT on this problem. 7.2-5 Suppose that the splits at every level of quicksort are in the proportion 1 ˛ to ˛, where 0<˛ 1=2 is a constant. Show that the minimum depth of a leaf in the re- cursion tree is approximately lg n= lg ˛ and the maximum depth is approximately lg n= lg.1 ˛/. (Don’t worry about integer round-off.)7.3 A randomized version of quicksort 179 7.2-6 ? Argue that for any constant 0<˛ 1=2, the probability is approximately 1 2˛ that on a random input array, PARTITION produces a split more balanced than 1˛ to ˛. 7.3 A randomized version of quicksort In exploring the average-case behavior of quicksort, we have made an assumption that all permutations of the input numbers are equally likely. In an engineering situation, however, we cannot always expect this assumption to hold. (See Exer- cise 7.2-4.) As we saw in Section 5.3, we can sometimes add randomization to an algorithm in order to obtain good expected performance over all inputs. Many peo- ple regard the resulting randomized version of quicksort as the sorting algorithm of choice for large enough inputs. In Section 5.3, we randomized our algorithm by explicitly permuting the in- put. We could do so for quicksort also, but a different randomization technique, called random sampling, yields a simpler analysis. Instead of always using AŒr as the pivot, we will select a randomly chosen element from the subarray AŒp : : r. We do so by ﬁrst exchanging element AŒr with an element chosen at random from AŒp : : r. By randomly sampling the range p;:::;r, we ensure that the pivot element x D AŒr is equally likely to be any of the r p C 1 elements in the subarray. Because we randomly choose the pivot element, we expect the split of the input array to be reasonably well balanced on average. The changes to PARTITION and QUICKSORT are small. In the new partition procedure, we simply implement the swap before actually partitioning: RANDOMIZED-PARTITION.A;p;r/ 1 i D RANDOM.p; r/ 2 exchange AŒr with AŒi 3 return PARTITION.A;p;r/ The new quicksort calls RANDOMIZED-PARTITION in place of PARTITION: RANDOMIZED-QUICKSORT.A;p;r/ 1 if paj to determine their relative order. We may not inspect the values of the elements or gain order information about them in any other way. In this section, we assume without loss of generality that all the input elements are distinct. Given this assumption, comparisons of the form ai D aj are useless, so we can assume that no comparisons of this form are made. We also note that the comparisons ai aj , ai aj , ai >aj ,andai ≤ > 1:2 2:3 1:3 〈1,2,3〉 1:3 〈2,1,3〉 2:3 〈1,3,2〉 〈3,1,2〉 〈3,2,1〉 ≤ > ≤ > ≤ > 〈2,3,1〉 Figure 8.1 The decision tree for insertion sort operating on three elements. An internal node an- notated by i:j indicates a comparison between ai and aj . A leaf annotated by the permutation h.1/; .2/; : : : ; .n/i indicates the ordering a.1/ a.2/ a.n/. The shaded path indicates the decisions made when sorting the input sequence ha1 D 6; a2 D 8; a3 D 5i;the permutation h3; 1; 2i at the leaf indicates that the sorted ordering is a3 D 5 a1 D 6 a2 D 8. There are 3Š D 6 possible permutations of the input elements, and so the decision tree must have at least 6 leaves. they yield identical information about the relative order of ai and aj . We therefore assume that all comparisons have the form ai aj . The decision-tree model We can view comparison sorts abstractly in terms of decision trees. A decision tree is a full binary tree that represents the comparisons between elements that are performed by a particular sorting algorithm operating on an input of a given size. Control, data movement, and all other aspects of the algorithm are ignored. Figure 8.1 shows the decision tree corresponding to the insertion sort algorithm from Section 2.1 operating on an input sequence of three elements. In a decision tree, we annotate each internal node by i:j for some i and j in the range 1 i;j n,wheren is the number of elements in the input sequence. We also annotate each leaf by a permutation h.1/; .2/; : : : ; .n/i. (See Section C.1 for background on permutations.) The execution of the sorting algorithm corre- sponds to tracing a simple path from the root of the decision tree down to a leaf. Each internal node indicates a comparison ai aj . The left subtree then dictates subsequent comparisons once we know that ai aj , and the right subtree dictates subsequent comparisons knowing that ai >aj . When we come to a leaf, the sort- ing algorithm has established the ordering a.1/ a.2/ a.n/. Because any correct sorting algorithm must be able to produce each permutation of its input, each of the nŠ permutations on n elements must appear as one of the leaves of the decision tree for a comparison sort to be correct. Furthermore, each of these leaves must be reachable from the root by a downward path corresponding to an actual8.1 Lower bounds for sorting 193 execution of the comparison sort. (We shall refer to such leaves as “reachable.”) Thus, we shall consider only decision trees in which each permutation appears as a reachable leaf. A lower bound for the worst case The length of the longest simple path from the root of a decision tree to any of its reachable leaves represents the worst-case number of comparisons that the cor- responding sorting algorithm performs. Consequently, the worst-case number of comparisons for a given comparison sort algorithm equals the height of its decision tree. A lower bound on the heights of all decision trees in which each permutation appears as a reachable leaf is therefore a lower bound on the running time of any comparison sort algorithm. The following theorem establishes such a lower bound. Theorem 8.1 Any comparison sort algorithm requires .n lg n/ comparisons in the worst case. Proof From the preceding discussion, it sufﬁces to determine the height of a decision tree in which each permutation appears as a reachable leaf. Consider a decision tree of height h with l reachable leaves corresponding to a comparison sort on n elements. Because each of the nŠ permutations of the input appears as some leaf, we have nŠ l. Since a binary tree of height h has no more than 2h leaves, we have nŠ l 2h ; which, by taking logarithms, implies h lg.nŠ/ (since the lg function is monotonically increasing) D .n lg n/ (by equation (3.19)) . Corollary 8.2 Heapsort and merge sort are asymptotically optimal comparison sorts. Proof The O.nlg n/ upper bounds on the running times for heapsort and merge sort match the .n lg n/ worst-case lower bound from Theorem 8.1. Exercises 8.1-1 What is the smallest possible depth of a leaf in a decision tree for a comparison sort?194 Chapter 8 Sorting in Linear Time 8.1-2 Obtain asymptotically tight bounds on lg.nŠ/ without using Stirling’s approxi- mation. Instead, evaluate the summation Pn kD1 lg k using techniques from Sec- tion A.2. 8.1-3 Show that there is no comparison sort whose running time is linear for at least half of the nŠ inputs of length n. What about a fraction of 1=n of the inputs of length n? What about a fraction 1=2n? 8.1-4 Suppose that you are given a sequence of n elements to sort. The input sequence consists of n=k subsequences, each containing k elements. The elements in a given subsequence are all smaller than the elements in the succeeding subsequence and larger than the elements in the preceding subsequence. Thus, all that is needed to sort the whole sequence of length n is to sort the k elements in each of the n=k subsequences. Show an .n lg k/ lower bound on the number of comparisons needed to solve this variant of the sorting problem. (Hint: It is not rigorous to simply combine the lower bounds for the individual subsequences.) 8.2 Counting sort Counting sort assumes that each of the n input elements is an integer in the range 0 to k, for some integer k.Whenk D O.n/, the sort runs in ‚.n/ time. Counting sort determines, for each input element x, the number of elements less than x. It uses this information to place element x directly into its position in the output array. For example, if 17 elements are less than x,thenx belongs in output position 18. We must modify this scheme slightly to handle the situation in which several elements have the same value, since we do not want to put them all in the same position. In the code for counting sort, we assume that the input is an array AŒ1 : : n,and thus A:length D n. We require two other arrays: the array BŒ1::n holds the sorted output, and the array CŒ0::kprovides temporary working storage.8.2 Counting sort 195 25302303 12345678 202301 12345 A C (a) 224778C (b) 3 12345678 224678 B C (c) 3 12345678 124678 B C (d) 0 3 12345678 124578 B C (e) 03 3 12345678 B (f) 030 223 5 0 123450 123450 123450 123450 Figure 8.2 The operation of COUNTING-SORT on an input array AŒ1::8, where each element of A is a nonnegative integer no larger than k D 5. (a) The array A and the auxiliary array C after line 5. (b) The array C after line 8. (c)–(e) The output array B and the auxiliary array C after one, two, and three iterations of the loop in lines 10–12, respectively. Only the lightly shaded elements of array B have been ﬁlled in. (f) The ﬁnal sorted output array B. COUNTING-SORT.A;B;k/ 1letCŒ0::kbeanewarray 2 for i D 0 to k 3 CŒi D 0 4 for j D 1 to A:length 5 C ŒAŒj D C ŒAŒj C 1 6 // CŒinow contains the number of elements equal to i. 7 for i D 1 to k 8 CŒi D CŒiC CŒi 1 9 // CŒinow contains the number of elements less than or equal to i. 10 for j D A:length downto 1 11 BŒC ŒAŒj D AŒj 12 C ŒAŒj D C ŒAŒj 1 Figure 8.2 illustrates counting sort. After the for loop of lines 2–3 initializes the array C to all zeros, the for loop of lines 4–5 inspects each input element. If the value of an input element is i, we increment CŒi. Thus, after line 5, CŒi holds the number of input elements equal to i for each integer i D 0; 1; : : : ; k. Lines 7–8 determine for each i D 0; 1; : : : ; k how many input elements are less than or equal to i by keeping a running sum of the array C.196 Chapter 8 Sorting in Linear Time Finally, the for loop of lines 10–12 places each element AŒj into its correct sorted position in the output array B.Ifalln elements are distinct, then when we ﬁrst enter line 10, for each AŒj ,thevalueC ŒAŒj is the correct ﬁnal position of AŒj in the output array, since there are C ŒAŒj elements less than or equal to AŒj . Because the elements might not be distinct, we decrement C ŒAŒj each time we place a value AŒj into the B array. Decrementing C ŒAŒj causes the next input element with a value equal to AŒj , if one exists, to go to the position immediately before AŒj in the output array. How much time does counting sort require? The for loop of lines 2–3 takes time ‚.k/,thefor loop of lines 4–5 takes time ‚.n/,thefor loop of lines 7–8 takes time ‚.k/,andthefor loop of lines 10–12 takes time ‚.n/. Thus, the overall time is ‚.k C n/. In practice, we usually use counting sort when we have k D O.n/,in which case the running time is ‚.n/. Counting sort beats the lower bound of .n lg n/ proved in Section 8.1 because it is not a comparison sort. In fact, no comparisons between input elements occur anywhere in the code. Instead, counting sort uses the actual values of the elements to index into an array. The .n lg n/ lower bound for sorting does not apply when we depart from the comparison sort model. An important property of counting sort is that it is stable: numbers with the same value appear in the output array in the same order as they do in the input array. That is, it breaks ties between two numbers by the rule that whichever number appears ﬁrst in the input array appears ﬁrst in the output array. Normally, the property of stability is important only when satellite data are carried around with the element being sorted. Counting sort’s stability is important for another reason: counting sort is often used as a subroutine in radix sort. As we shall see in the next section, in order for radix sort to work correctly, counting sort must be stable. Exercises 8.2-1 Using Figure 8.2 as a model, illustrate the operation of COUNTING-SORT on the array A Dh6; 0; 2; 0; 1; 3; 4; 6; 1; 3; 2i. 8.2-2 Prove that COUNTING-SORT is stable. 8.2-3 Suppose that we were to rewrite the for loop header in line 10 of the COUNTING- SORT as 10 for j D 1 to A:length Show that the algorithm still works properly. Is the modiﬁed algorithm stable?8.3 Radix sort 197 8.2-4 Describe an algorithm that, given n integers in the range 0 to k, preprocesses its input and then answers any query about how many of the n integers fall into a range Œa::b in O.1/ time. Your algorithm should use ‚.n C k/ preprocessing time. 8.3 Radix sort Radix sort is the algorithm used by the card-sorting machines you now ﬁnd only in computer museums. The cards have 80 columns, and in each column a machine can punch a hole in one of 12 places. The sorter can be mechanically “programmed” to examine a given column of each card in a deck and distribute the card into one of 12 bins depending on which place has been punched. An operator can then gather the cards bin by bin, so that cards with the ﬁrst place punched are on top of cards with the second place punched, and so on. For decimal digits, each column uses only 10 places. (The other two places are reserved for encoding nonnumeric characters.) A d-digit number would then occupy a ﬁeld of d columns. Since the card sorter can look at only one column at a time, the problem of sorting n cards on a d-digit number requires a sorting algorithm. Intuitively, you might sort numbers on their most signiﬁcant digit, sort each of the resulting bins recursively, and then combine the decks in order. Unfortunately, since the cards in 9 of the 10 bins must be put aside to sort each of the bins, this procedure generates many intermediate piles of cards that you would have to keep track of. (See Exercise 8.3-5.) Radix sort solves the problem of card sorting—counterintuitively—by sorting on the least signiﬁcant digit ﬁrst. The algorithm then combines the cards into a single deck, with the cards in the 0 bin preceding the cards in the 1 bin preceding the cards in the 2 bin, and so on. Then it sorts the entire deck again on the second-least signiﬁcant digit and recombines the deck in a like manner. The process continues until the cards have been sorted on all d digits. Remarkably, at that point the cards are fully sorted on the d-digit number. Thus, only d passes through the deck are required to sort. Figure 8.3 shows how radix sort operates on a “deck” of seven 3-digit numbers. In order for radix sort to work correctly, the digit sorts must be stable. The sort performed by a card sorter is stable, but the operator has to be wary about not changing the order of the cards as they come out of a bin, even though all the cards in a bin have the same digit in the chosen column.198 Chapter 8 Sorting in Linear Time 329 457 657 839 436 720 355 329 457 657 839 436 720 355 329 457 657 839 436 720 355 329 457 657 839 436 720 355 Figure 8.3 The operation of radix sort on a list of seven 3-digit numbers. The leftmost column is the input. The remaining columns show the list after successive sorts on increasingly signiﬁcant digit positions. Shading indicates the digit position sorted on to produce each list from the previous one. In a typical computer, which is a sequential random-access machine, we some- times use radix sort to sort records of information that are keyed by multiple ﬁelds. For example, we might wish to sort dates by three keys: year, month, and day. We could run a sorting algorithm with a comparison function that, given two dates, compares years, and if there is a tie, compares months, and if another tie occurs, compares days. Alternatively, we could sort the information three times with a stable sort: ﬁrst on day, next on month, and ﬁnally on year. The code for radix sort is straightforward. The following procedure assumes that each element in the n-element array A has d digits, where digit 1 is the lowest-order digit and digit d is the highest-order digit. RADIX-SORT.A; d/ 1 for i D 1 to d 2 use a stable sort to sort array A on digit i Lemma 8.3 Given nd-digit numbers in which each digit can take on up to k possible values, RADIX-SORT correctly sorts these numbers in ‚.d.n C k// time if the stable sort it uses takes ‚.n C k/ time. Proof The correctness of radix sort follows by induction on the column being sorted (see Exercise 8.3-3). The analysis of the running time depends on the stable sort used as the intermediate sorting algorithm. When each digit is in the range 0 to k1 (so that it can take on k possible values), and k is not too large, counting sort is the obvious choice. Each pass over nd-digit numbers then takes time ‚.nCk/. There are d passes, and so the total time for radix sort is ‚.d.n C k//. When d is constant and k D O.n/, we can make radix sort run in linear time. More generally, we have some ﬂexibility in how to break each key into digits.8.3 Radix sort 199 Lemma 8.4 Given nb-bit numbers and any positive integer r b,RADIX-SORT correctly sorts these numbers in ‚..b=r/.n C 2r // time if the stable sort it uses takes ‚.n C k/ time for inputs in the range 0 to k. Proof For a value r b, we view each key as having d D db=re digits of r bits each. Each digit is an integer in the range 0 to 2r 1, so that we can use counting sort with k D 2r 1. (For example, we can view a 32-bit word as having four 8-bit digits, so that b D 32, r D 8, k D 2r 1 D 255,andd D b=r D 4.) Each pass of counting sort takes time ‚.n C k/ D ‚.n C 2r / and there are d passes, for a total running time of ‚.d.n C 2r // D ‚..b=r/.n C 2r //. For given values of n and b, we wish to choose the value of r, with r b, that minimizes the expression .b=r/.n C 2r /.Ifb1leaves, and let LT and RT be the left and right subtrees of T . Show that D.T / D D.LT/ C D.RT/ C k. c. Let d.k/ be the minimum value of D.T / over all decision trees T with k>1 leaves. Show that d.k/ D min1ik1 fd.i/ C d.k i/C kg.(Hint: Consider a decision tree T with k leaves that achieves the minimum. Let i0 be the number of leaves in LT and k i0 the number of leaves in RT.) d. Prove that for a given value of k>1and i in the range 1 i k 1,the function i lg i C .k i/lg.k i/ is minimized at i D k=2. Conclude that d.k/ D .k lg k/. e. Prove that D.TA/ D .nŠ lg.nŠ//, and conclude that the average-case time to sort n elements is .n lg n/. Now, consider a randomized comparison sort B. We can extend the decision- tree model to handle randomization by incorporating two kinds of nodes: ordinary comparison nodes and “randomization” nodes. A randomization node models a random choice of the form RANDOM.1; r/ made by algorithm B; the node has r children, each of which is equally likely to be chosen during an execution of the algorithm. f. Show that for any randomized comparison sort B, there exists a deterministic comparison sort A whose expected number of comparisons is no more than those made by B.206 Chapter 8 Sorting in Linear Time 8-2 Sorting in place in linear time Suppose that we have an array of n data records to sort and that the key of each record has the value 0 or 1. An algorithm for sorting such a set of records might possess some subset of the following three desirable characteristics: 1. The algorithm runs in O.n/ time. 2. The algorithm is stable. 3. The algorithm sorts in place, using no more than a constant amount of storage space in addition to the original array. a. Give an algorithm that satisﬁes criteria 1 and 2 above. b. Give an algorithm that satisﬁes criteria 1 and 3 above. c. Give an algorithm that satisﬁes criteria 2 and 3 above. d. Can you use any of your sorting algorithms from parts (a)–(c) as the sorting method used in line 2 of RADIX-SORT,sothatRADIX-SORT sorts n records with b-bit keys in O.bn/ time? Explain how or why not. e. Suppose that the n records have keys in the range from 1 to k.Showhowto modify counting sort so that it sorts the records in place in O.nC k/ time. You may use O.k/ storage outside the input array. Is your algorithm stable? (Hint: How would you do it for k D 3?) 8-3 Sorting variable-length items a. You are given an array of integers, where different integers may have different numbers of digits, but the total number of digits over all the integers in the array is n. Show how to sort the array in O.n/ time. b. You are given an array of strings, where different strings may have different numbers of characters, but the total number of characters over all the strings is n. Show how to sort the strings in O.n/ time. (Note that the desired order here is the standard alphabetical order; for example, a < ab < b.) 8-4 Water jugs Suppose that you are given n red and n blue water jugs, all of different shapes and sizes. All red jugs hold different amounts of water, as do the blue ones. Moreover, for every red jug, there is a blue jug that holds the same amount of water, and vice versa.Problems for Chapter 8 207 Your task is to ﬁnd a grouping of the jugs into pairs of red and blue jugs that hold the same amount of water. To do so, you may perform the following operation: pick a pair of jugs in which one is red and one is blue, ﬁll the red jug with water, and then pour the water into the blue jug. This operation will tell you whether the red or the blue jug can hold more water, or that they have the same volume. Assume that such a comparison takes one time unit. Your goal is to ﬁnd an algorithm that makes a minimum number of comparisons to determine the grouping. Remember that you may not directly compare two red jugs or two blue jugs. a. Describe a deterministic algorithm that uses ‚.n2/ comparisons to group the jugs into pairs. b. Prove a lower bound of .n lg n/ for the number of comparisons that an algo- rithm solving this problem must make. c. Give a randomized algorithm whose expected number of comparisons is O.nlg n/, and prove that this bound is correct. What is the worst-case num- ber of comparisons for your algorithm? 8-5 Average sorting Suppose that, instead of sorting an array, we just require that the elements increase on average. More precisely, we call an n-element array A k-sorted if, for all i D 1;2;:::;n k, the following holds:PiCk1 jDi AŒj k PiCk jDiC1 AŒj k : a. What does it mean for an array to be 1-sorted? b. Give a permutation of the numbers 1;2;:::;10that is 2-sorted, but not sorted. c. Prove that an n-element array is k-sorted if and only if AŒi AŒi C k for all i D 1;2;:::;n k. d. Give an algorithm that k-sorts an n-element array in O.nlg.n=k// time. We can also show a lower bound on the time to produce a k-sorted array, when k is a constant. e. Show that we can sort a k-sorted array of length n in O.nlg k/ time. (Hint: Use the solution to Exercise 6.5-9. ) f. Show that when k is a constant, k-sorting an n-element array requires .n lg n/ time. (Hint: Use the solution to the previous part along with the lower bound on comparison sorts.)208 Chapter 8 Sorting in Linear Time 8-6 Lower bound on merging sorted lists The problem of merging two sorted lists arises frequently. We have seen a pro- cedure for it as the subroutine MERGE in Section 2.3.1. In this problem, we will prove a lower bound of 2n 1 on the worst-case number of comparisons required to merge two sorted lists, each containing n items. First we will show a lower bound of 2n o.n/ comparisons by using a decision tree. a. Given 2n numbers, compute the number of possible ways to divide them into two sorted lists, each with n numbers. b. Using a decision tree and your answer to part (a), show that any algorithm that correctly merges two sorted lists must perform at least 2n o.n/ comparisons. Now we will show a slightly tighter 2n 1 bound. c. Show that if two elements are consecutive in the sorted order and from different lists, then they must be compared. d. Use your answer to the previous part to show a lower bound of 2n 1 compar- isons for merging two sorted lists. 8-7 The 0-1 sorting lemma and columnsort A compare-exchange operation on two array elements AŒi and AŒj ,wherei AŒj 2 exchange AŒi with AŒj After the compare-exchange operation, we know that AŒi AŒj . An oblivious compare-exchange algorithm operates solely by a sequence of prespeciﬁed compare-exchange operations. The indices of the positions compared in the sequence must be determined in advance, and although they can depend on the number of elements being sorted, they cannot depend on the values being sorted, nor can they depend on the result of any prior compare-exchange operation. For example, here is insertion sort expressed as an oblivious compare-exchange algorithm: INSERTION-SORT.A/ 1 for j D 2 to A:length 2 for i D j 1 downto 1 3COMPARE-EXCHANGE.A;i;i C 1/Problems for Chapter 8 209 The 0-1 sorting lemma provides a powerful way to prove that an oblivious compare-exchange algorithm produces a sorted result. It states that if an oblivi- ous compare-exchange algorithm correctly sorts all input sequences consisting of only 0s and 1s, then it correctly sorts all inputs containing arbitrary values. You will prove the 0-1 sorting lemma by proving its contrapositive: if an oblivi- ous compare-exchange algorithm fails to sort an input containing arbitrary values, then it fails to sort some 0-1 input. Assume that an oblivious compare-exchange al- gorithm X fails to correctly sort the array AŒ1 : : n.LetAŒp be the smallest value in A that algorithm X puts into the wrong location, and let AŒq be the value that algorithm X moves to the location into which AŒp should have gone. Deﬁne an array BŒ1::nof 0s and 1s as follows: BŒi D ( 0 if AŒi AŒp ; 1 if AŒi > AŒp : a. Argue that AŒq > AŒp,sothatBŒp D 0 and BŒq D 1. b. To complete the proof of the 0-1 sorting lemma, prove that algorithm X fails to sort array B correctly. Now you will use the 0-1 sorting lemma to prove that a particular sorting algo- rithm works correctly. The algorithm, columnsort, works on a rectangular array of n elements. The array has r rows and s columns (so that n D rs), subject to three restrictions: r must be even, s must be a divisor of r,and r 2s2. When columnsort completes, the array is sorted in column-major order: reading down the columns, from left to right, the elements monotonically increase. Columnsort operates in eight steps, regardless of the value of n. The odd steps are all the same: sort each column individually. Each even step is a ﬁxed permuta- tion. Here are the steps: 1. Sort each column. 2. Transpose the array, but reshape it back to r rows and s columns. In other words, turn the leftmost column into the top r=s rows, in order; turn the next column into the next r=s rows, in order; and so on. 3. Sort each column. 4. Perform the inverse of the permutation performed in step 2.210 Chapter 8 Sorting in Linear Time 10 14 5 8717 12 1 6 16 9 11 4152 18 3 13 (a) 412 835 10 7 6 12 9 11 16 14 13 18 15 17 (b) 4810 12 16 18 137 91415 256 11 13 17 (c) 136 257 4810 91315 11 14 17 12 16 18 (d) 1411 3814 61017 2912 51316 71518 (e) 1411 2812 3914 51016 61317 71518 (f) 51016 61317 71518 1411 2812 3914 (g) 41016 51117 61218 1713 2814 3915 (h) 1713 2814 3915 41016 51117 61218 (i) Figure 8.5 The steps of columnsort. (a) The input array with 6 rows and 3 columns. (b) After sorting each column in step 1. (c) After transposing and reshaping in step 2. (d) After sorting each columninstep3.(e) After performing step 4, which inverts the permutation from step 2. (f) After sorting each column in step 5. (g) After shifting by half a column in step 6. (h) After sorting each column in step 7. (i) After performing step 8, which inverts the permutation from step 6. The array is now sorted in column-major order. 5. Sort each column. 6. Shift the top half of each column into the bottom half of the same column, and shift the bottom half of each column into the top half of the next column to the right. Leave the top half of the leftmost column empty. Shift the bottom half of the last column into the top half of a new rightmost column, and leave the bottom half of this new column empty. 7. Sort each column. 8. Perform the inverse of the permutation performed in step 6. Figure 8.5 shows an example of the steps of columnsort with r D 6 and s D 3. (Even though this example violates the requirement that r 2s2, it happens to work.) c. Argue that we can treat columnsort as an oblivious compare-exchange algo- rithm, even if we do not know what sorting method the odd steps use. Although it might seem hard to believe that columnsort actually sorts, you will use the 0-1 sorting lemma to prove that it does. The 0-1 sorting lemma applies because we can treat columnsort as an oblivious compare-exchange algorithm. ANotes for Chapter 8 211 couple of deﬁnitions will help you apply the 0-1 sorting lemma. We say that an area of an array is clean if we know that it contains either all 0s or all 1s. Otherwise, the area might contain mixed 0s and 1s, and it is dirty. From here on, assume that the input array contains only 0s and 1s, and that we can treat it as an array with r rows and s columns. d. Prove that after steps 1–3, the array consists of some clean rows of 0s at the top, some clean rows of 1s at the bottom, and at most s dirty rows between them. e. Prove that after step 4, the array, read in column-major order, starts with a clean area of 0s, ends with a clean area of 1s, and has a dirty area of at most s2 elements in the middle. f. Prove that steps 5–8 produce a fully sorted 0-1 output. Conclude that column- sort correctly sorts all inputs containing arbitrary values. g. Now suppose that s does not divide r. Prove that after steps 1–3, the array consists of some clean rows of 0s at the top, some clean rows of 1s at the bottom, and at most 2s 1 dirty rows between them. How large must r be, compared with s, for columnsort to correctly sort when s does not divide r? h. Suggest a simple change to step 1 that allows us to maintain the requirement that r 2s2 even when s does not divide r, and prove that with your change, columnsort correctly sorts. Chapter notes The decision-tree model for studying comparison sorts was introduced by Ford and Johnson [110]. Knuth’s comprehensive treatise on sorting [211] covers many variations on the sorting problem, including the information-theoretic lower bound on the complexity of sorting given here. Ben-Or [39] studied lower bounds for sorting using generalizations of the decision-tree model. Knuth credits H. H. Seward with inventing counting sort in 1954, as well as with the idea of combining counting sort with radix sort. Radix sorting starting with the least signiﬁcant digit appears to be a folk algorithm widely used by operators of mechanical card-sorting machines. According to Knuth, the ﬁrst published refer- ence to the method is a 1929 document by L. J. Comrie describing punched-card equipment. Bucket sorting has been in use since 1956, when the basic idea was proposed by E. J. Isaac and R. C. Singleton [188]. Munro and Raman [263] give a stable sorting algorithm that performs O.n1C/ comparisons in the worst case, where 0< 1 is any ﬁxed constant. Although212 Chapter 8 Sorting in Linear Time any of the O.nlg n/-time algorithms make fewer comparisons, the algorithm by Munro and Raman moves data only O.n/ times and operates in place. The case of sorting nb-bit integers in o.nlg n/ time has been considered by many researchers. Several positive results have been obtained, each under slightly different assumptions about the model of computation and the restrictions placed on the algorithm. All the results assume that the computer memory is divided into addressable b-bit words. Fredman and Willard [115] introduced the fusion tree data structure and used it to sort n integers in O.nlg n= lg lg n/ time. This bound was later improved to O.n p lg n/ time by Andersson [16]. These algorithms require the use of multiplication and several precomputed constants. Andersson, Hagerup, Nilsson, and Raman [17] have shown how to sort n integers in O.nlg lg n/ time without using multiplication, but their method requires storage that can be un- bounded in terms of n. Using multiplicative hashing, we can reduce the storage needed to O.n/, but then the O.nlg lg n/ worst-case bound on the running time becomes an expected-time bound. Generalizing the exponential search trees of Andersson [16], Thorup [335] gave an O.n.lg lg n/2/-time sorting algorithm that does not use multiplication or randomization, and it uses linear space. Combining these techniques with some new ideas, Han [158] improved the bound for sorting to O.nlg lg n lg lg lg n/ time. Although these algorithms are important theoretical breakthroughs, they are all fairly complicated and at the present time seem unlikely to compete with existing sorting algorithms in practice. The columnsort algorithm in Problem 8-7 is by Leighton [227].9 Medians and Order Statistics The ith order statistic of a set of n elements is the ith smallest element. For example, the minimum of a set of elements is the ﬁrst order statistic (i D 1), and the maximum is the nth order statistic (i D n). A median, informally, is the “halfway point” of the set. When n is odd, the median is unique, occurring at i D .n C 1/=2.Whenn is even, there are two medians, occurring at i D n=2 and i D n=2C1. Thus, regardless of the parity of n, medians occur at i D b.n C 1/=2c (the lower median)andi D d.n C 1/=2e (the upper median). For simplicity in this text, however, we consistently use the phrase “the median” to refer to the lower median. This chapter addresses the problem of selecting the ith order statistic from a set of n distinct numbers. We assume for convenience that the set contains dis- tinct numbers, although virtually everything that we do extends to the situation in which a set contains repeated values. We formally specify the selection problem as follows: Input: A set A of n (distinct) numbers and an integer i, with 1 i n. Output: The element x 2 A that is larger than exactly i 1 other elements of A. We can solve the selection problem in O.nlg n/ time, since we can sort the num- bers using heapsort or merge sort and then simply index the ith element in the output array. This chapter presents faster algorithms. In Section 9.1, we examine the problem of selecting the minimum and maxi- mum of a set of elements. More interesting is the general selection problem, which we investigate in the subsequent two sections. Section 9.2 analyzes a practical randomized algorithm that achieves an O.n/ expected running time, assuming dis- tinct elements. Section 9.3 contains an algorithm of more theoretical interest that achieves the O.n/ running time in the worst case.214 Chapter 9 Medians and Order Statistics 9.1 Minimum and maximum How many comparisons are necessary to determine the minimum of a set of n elements? We can easily obtain an upper bound of n 1 comparisons: examine each element of the set in turn and keep track of the smallest element seen so far. In the following procedure, we assume that the set resides in array A,where A:length D n. MINIMUM.A/ 1 min D AŒ1 2 for i D 2 to A:length 3 if min > AŒi 4 min D AŒi 5 return min We can, of course, ﬁnd the maximum with n 1 comparisons as well. Is this the best we can do? Yes, since we can obtain a lower bound of n 1 comparisons for the problem of determining the minimum. Think of any algorithm that determines the minimum as a tournament among the elements. Each compar- ison is a match in the tournament in which the smaller of the two elements wins. Observing that every element except the winner must lose at least one match, we conclude that n 1 comparisons are necessary to determine the minimum. Hence, the algorithm MINIMUM is optimal with respect to the number of comparisons performed. Simultaneous minimum and maximum In some applications, we must ﬁnd both the minimum and the maximum of a set of n elements. For example, a graphics program may need to scale a set of .x; y/ data to ﬁt onto a rectangular display screen or other graphical output device. To do so, the program must ﬁrst determine the minimum and maximum value of each coordinate. At this point, it should be obvious how to determine both the minimum and the maximum of n elements using ‚.n/ comparisons, which is asymptotically optimal: simply ﬁnd the minimum and maximum independently, using n 1 comparisons for each, for a total of 2n 2 comparisons. In fact, we can ﬁnd both the minimum and the maximum using at most 3 bn=2c comparisons. We do so by maintaining both the minimum and maximum elements seen thus far. Rather than processing each element of the input by comparing it against the current minimum and maximum, at a cost of 2 comparisons per element,9.2 Selection in expected linear time 215 we process elements in pairs. We compare pairs of elements from the input ﬁrst with each other, and then we compare the smaller with the current minimum and the larger to the current maximum, at a cost of 3 comparisons for every 2 elements. How we set up initial values for the current minimum and maximum depends on whether n is odd or even. If n is odd, we set both the minimum and maximum to the value of the ﬁrst element, and then we process the rest of the elements in pairs. If n is even, we perform 1 comparison on the ﬁrst 2 elements to determine the initial values of the minimum and maximum, and then process the rest of the elements in pairs as in the case for odd n. Let us analyze the total number of comparisons. If n is odd, then we perform 3 bn=2c comparisons. If n is even, we perform 1 initial comparison followed by 3.n 2/=2 comparisons, for a total of 3n=2 2. Thus, in either case, the total number of comparisons is at most 3 bn=2c. Exercises 9.1-1 Show that the second smallest of n elements can be found with n C dlg ne 2 comparisons in the worst case. (Hint: Also ﬁnd the smallest element.) 9.1-2 ? Prove the lower bound of d3n=2e 2 comparisons in the worst case to ﬁnd both the maximum and minimum of n numbers. (Hint: Consider how many numbers are potentially either the maximum or minimum, and investigate how a comparison affects these counts.) 9.2 Selection in expected linear time The general selection problem appears more difﬁcult than the simple problem of ﬁnding a minimum. Yet, surprisingly, the asymptotic running time for both prob- lems is the same: ‚.n/. In this section, we present a divide-and-conquer algorithm for the selection problem. The algorithm RANDOMIZED-SELECT is modeled after the quicksort algorithm of Chapter 7. As in quicksort, we partition the input array recursively. But unlike quicksort, which recursively processes both sides of the partition, RANDOMIZED-SELECT works on only one side of the partition. This difference shows up in the analysis: whereas quicksort has an expected running time of ‚.n lg n/, the expected running time of RANDOMIZED-SELECT is ‚.n/, assuming that the elements are distinct.216 Chapter 9 Medians and Order Statistics RANDOMIZED-SELECT uses the procedure RANDOMIZED-PARTITION intro- duced in Section 7.3. Thus, like RANDOMIZED-QUICKSORT, it is a randomized al- gorithm, since its behavior is determined in part by the output of a random-number generator. The following code for RANDOMIZED-SELECT returns the ith smallest element of the array AŒp : : r. RANDOMIZED-SELECT.A;p;r;i/ 1 if p == r 2 return AŒp 3 q D RANDOMIZED-PARTITION.A;p;r/ 4 k D q p C 1 5 if i == k // the pivot value is the answer 6 return AŒq 7 elseif ik,however, then the desired element lies on the high side of the partition. Since we already know k values that are smaller than the ith smallest element of AŒp : : r—namely, the elements of AŒp : : q—the desired element is the .i k/th smallest element of AŒq C1::r, which line 9 ﬁnds recursively. The code appears to allow recursive calls to subarrays with 0 elements, but Exercise 9.2-1 asks you to show that this situation cannot happen. The worst-case running time for RANDOMIZED-SELECT is ‚.n2/,eventoﬁnd the minimum, because we could be extremely unlucky and always partition around the largest remaining element, and partitioning takes ‚.n/ time. We will see that9.2 Selection in expected linear time 217 the algorithm has a linear expected running time, though, and because it is random- ized, no particular input elicits the worst-case behavior. To analyze the expected running time of RANDOMIZED-SELECT, we let the run- ning time on an input array AŒp : : r of n elements be a random variable that we denote by T .n/, and we obtain an upper bound on E ŒT .n/ as follows. The pro- cedure RANDOMIZED-PARTITION is equally likely to return any element as the pivot. Therefore, for each k such that 1 k n, the subarray AŒp : : q has k ele- ments (all less than or equal to the pivot) with probability 1=n.Fork D 1;2;:::;n, we deﬁne indicator random variables Xk where Xk D I fthe subarray AŒp : : q has exactly k elementsg ; and so, assuming that the elements are distinct, we have E ŒXk D 1=n : (9.1) When we call RANDOMIZED-SELECT and choose AŒq as the pivot element, we do not know, a priori, if we will terminate immediately with the correct answer, recurse on the subarray AŒp : : q 1, or recurse on the subarray AŒq C 1::r. This decision depends on where the ith smallest element falls relative to AŒq. Assuming that T .n/ is monotonically increasing, we can upper-bound the time needed for the recursive call by the time needed for the recursive call on the largest possible input. In other words, to obtain an upper bound, we assume that the ith element is always on the side of the partition with the greater number of elements. For a given call of RANDOMIZED-SELECT, the indicator random variable Xk has the value 1 for exactly one value of k, and it is 0 for all other k.WhenXk D 1,the two subarrays on which we might recurse have sizes k 1 and n k. Hence, we have the recurrence T .n/ nX kD1 Xk .T .max.k 1; n k// C O.n// D nX kD1 Xk T.max.k 1; n k// C O.n/ :218 Chapter 9 Medians and Order Statistics Taking expected values, we have E ŒT .n/ E " nX kD1 Xk T.max.k 1; n k// C O.n/ # D nX kD1 E ŒXk T.max.k 1; n k// C O.n/ (by linearity of expectation) D nX kD1 E ŒXk E ŒT .max.k 1; n k// C O.n/ (by equation (C.24)) D nX kD1 1 n E ŒT .max.k 1; n k// C O.n/ (by equation (9.1)) . In order to apply equation (C.24), we rely on Xk and T.max.k 1; n k// being independent random variables. Exercise 9.2-2 asks you to justify this assertion. Let us consider the expression max.k 1; n k/.Wehave max.k 1; n k/ D ( k 1 if k>dn=2e ; n k if k dn=2e : If n is even, each term from T.dn=2e/ up to T.n 1/ appears exactly twice in the summation, and if n is odd, all these terms appear twice and T.bn=2c/ appears once. Thus, we have E ŒT .n/ 2 n n1X kDbn=2c E ŒT .k/ C O.n/ : We show that E ŒT .n/ D O.n/ by substitution. Assume that E ŒT .n/ cn for some constant c that satisﬁes the initial conditions of the recurrence. We assume that T .n/ D O.1/ for n less than some constant; we shall pick this constant later. We also pick a constant a such that the function described by the O.n/ term above (which describes the non-recursive component of the running time of the algo- rithm) is bounded from above by an for all n>0. Using this inductive hypothesis, we have E ŒT .n/ 2 n n1X kDbn=2c ck C an D 2c n n1X kD1 k bn=2c1X kD1 k ! C an9.2 Selection in expected linear time 219 D 2c n .n 1/n 2 .bn=2c 1/ bn=2c 2 C an 2c n .n 1/n 2 .n=2 2/.n=2 1/ 2 C an D 2c n n2 n 2 n2=4 3n=2 C 2 2 C an D c n 3n2 4 C n 2 2 C an D c 3n 4 C 1 2 2 n C an 3cn 4 C c 2 C an D cn cn 4 c 2 an : In order to complete the proof, we need to show that for sufﬁciently large n,this last expression is at most cn or, equivalently, that cn=4 c=2 an 0.Ifwe add c=2 to both sides and factor out n,wegetn.c=4 a/ c=2. As long as we choose the constant c so that c=4 a>0, i.e., c>4a, we can divide both sides by c=4 a,giving n c=2 c=4 a D 2c c 4a : Thus, if we assume that T .n/ D O.1/ for n<2c=.c4a/,thenEŒT .n/ D O.n/. We conclude that we can ﬁnd any order statistic, and in particular the median, in expected linear time, assuming that the elements are distinct. Exercises 9.2-1 Show that RANDOMIZED-SELECT never makes a recursive call to a 0-length array. 9.2-2 Argue that the indicator random variable Xk and the value T.max.k 1; n k// are independent. 9.2-3 Write an iterative version of RANDOMIZED-SELECT.220 Chapter 9 Medians and Order Statistics 9.2-4 Suppose we use RANDOMIZED-SELECT to select the minimum element of the array A Dh3; 2; 9; 0; 7; 5; 4; 8; 6; 1i. Describe a sequence of partitions that results in a worst-case performance of RANDOMIZED-SELECT. 9.3 Selection in worst-case linear time We now examine a selection algorithm whose running time is O.n/ in the worst case. Like RANDOMIZED-SELECT, the algorithm SELECT ﬁnds the desired ele- ment by recursively partitioning the input array. Here, however, we guarantee a good split upon partitioning the array. SELECT uses the deterministic partitioning algorithm PARTITION from quicksort (see Section 7.1), but modiﬁed to take the element to partition around as an input parameter. The SELECT algorithm determines the ith smallest of an input array of n>1 distinct elements by executing the following steps. (If n D 1,thenSELECT merely returns its only input value as the ith smallest.) 1. Divide the n elements of the input array into bn=5c groups of 5 elements each and at most one group made up of the remaining n mod 5 elements. 2. Find the median of each of the dn=5e groups by ﬁrst insertion-sorting the ele- ments of each group (of which there are at most 5) and then picking the median from the sorted list of group elements. 3. Use SELECT recursively to ﬁnd the median x of the dn=5e medians found in step 2. (If there are an even number of medians, then by our convention, x is the lower median.) 4. Partition the input array around the median-of-medians x using the modiﬁed version of PARTITION.Letk be one more than the number of elements on the low side of the partition, so that x is the kth smallest element and there are nk elements on the high side of the partition. 5. If i D k, then return x. Otherwise, use SELECT recursively to ﬁnd the ith smallest element on the low side if ik. To analyze the running time of SELECT, we ﬁrst determine a lower bound on the number of elements that are greater than the partitioning element x. Figure 9.1 helps us to visualize this bookkeeping. At least half of the medians found in9.3 Selection in worst-case linear time 221 x Figure 9.1 Analysis of the algorithm SELECT.Then elements are represented by small circles, and each group of 5 elements occupies a column. The medians of the groups are whitened, and the median-of-medians x is labeled. (When ﬁnding the median of an even number of elements, we use the lower median.) Arrows go from larger elements to smaller, from which we can see that 3 out of every full group of 5 elements to the right of x are greater than x,and3 out of every group of 5 elements to the left of x are less than x. The elements known to be greater than x appear on a shaded background. step 2 are greater than or equal to the median-of-medians x.1 Thus, at least half of the dn=5e groups contribute at least 3 elements that are greater than x, except for the one group that has fewer than 5 elements if 5 does not divide n exactly, and the one group containing x itself. Discounting these two groups, it follows that the number of elements greater than x is at least 3 1 2 ln 5 m 2 3n 10 6: Similarly, at least 3n=10 6 elements are less than x. Thus, in the worst case, step 5 calls SELECT recursively on at most 7n=10 C 6 elements. We can now develop a recurrence for the worst-case running time T .n/ of the algorithm SELECT. Steps 1, 2, and 4 take O.n/ time. (Step 2 consists of O.n/ calls of insertion sort on sets of size O.1/.) Step 3 takes time T.dn=5e/, and step 5 takes time at most T.7n=10 C 6/, assuming that T is monotonically increasing. We make the assumption, which seems unmotivated at ﬁrst, that any input of fewer than 140 elements requires O.1/ time; the origin of the magic constant 140 will be clear shortly. We can therefore obtain the recurrence 1Because of our assumption that the numbers are distinct, all medians except x are either greater than or less than x.222 Chapter 9 Medians and Order Statistics T .n/ ( O.1/ if n < 140 ; T.dn=5e/ C T.7n=10C 6/ C O.n/ if n 140 : We show that the running time is linear by substitution. More speciﬁcally, we will show that T .n/ cn for some suitably large constant c and all n>0.Webeginby assuming that T .n/ cn for some suitably large constant c and all n < 140;this assumption holds if c is large enough. We also pick a constant a such that the func- tion described by the O.n/ term above (which describes the non-recursive compo- nent of the running time of the algorithm) is bounded above by an for all n>0. Substituting this inductive hypothesis into the right-hand side of the recurrence yields T .n/ c dn=5e C c.7n=10 C 6/ C an cn=5 C c C 7cn=10 C 6c C an D 9cn=10 C 7c C an D cn C .cn=10 C 7c C an/ ; which is at most cn if cn=10 C 7c C an 0: (9.2) Inequality (9.2) is equivalent to the inequality c 10a.n=.n 70// when n>70. Because we assume that n 140,wehaven=.n 70/ 2, and so choos- ing c 20a will satisfy inequality (9.2). (Note that there is nothing special about the constant 140; we could replace it by any integer strictly greater than 70 and then choose c accordingly.) The worst-case running time of SELECT is therefore linear. As in a comparison sort (see Section 8.1), SELECT and RANDOMIZED-SELECT determine information about the relative order of elements only by comparing ele- ments. Recall from Chapter 8 that sorting requires .n lg n/ time in the compari- son model, even on average (see Problem 8-1). The linear-time sorting algorithms in Chapter 8 make assumptions about the input. In contrast, the linear-time se- lection algorithms in this chapter do not require any assumptions about the input. They are not subject to the .n lg n/ lower bound because they manage to solve the selection problem without sorting. Thus, solving the selection problem by sort- ing and indexing, as presented in the introduction to this chapter, is asymptotically inefﬁcient.9.3 Selection in worst-case linear time 223 Exercises 9.3-1 In the algorithm SELECT, the input elements are divided into groups of 5. Will the algorithm work in linear time if they are divided into groups of 7? Argue that SELECT does not run in linear time if groups of 3 are used. 9.3-2 Analyze SELECT to show that if n 140, then at least dn=4e elements are greater than the median-of-medians x and at least dn=4e elements are less than x. 9.3-3 Show how quicksort can be made to run in O.nlg n/ time in the worst case, as- suming that all elements are distinct. 9.3-4 ? Suppose that an algorithm uses only comparisons to ﬁnd the ith smallest element in a set of n elements. Show that it can also ﬁnd the i 1 smaller elements and the n i larger elements without performing any additional comparisons. 9.3-5 Suppose that you have a “black-box” worst-case linear-time median subroutine. Give a simple, linear-time algorithm that solves the selection problem for an arbi- trary order statistic. 9.3-6 The kth quantiles of an n-element set are the k 1 order statistics that divide the sorted set into k equal-sized sets (to within 1). Give an O.nlg k/-time algorithm to list the kth quantiles of a set. 9.3-7 Describe an O.n/-time algorithm that, given a set S of n distinct numbers and a positive integer k n, determines the k numbers in S that are closest to the median of S. 9.3-8 Let XŒ1::n and YŒ1::n be two arrays, each containing n numbers already in sorted order. Give an O.lg n/-time algorithm to ﬁnd the median of all 2n elements in arrays X and Y . 9.3-9 Professor Olay is consulting for an oil company, which is planning a large pipeline running east to west through an oil ﬁeld of n wells. The company wants to connect224 Chapter 9 Medians and Order Statistics Figure 9.2 Professor Olay needs to determine the position of the east-west oil pipeline that mini- mizes the total length of the north-south spurs. a spur pipeline from each well directly to the main pipeline along a shortest route (either north or south), as shown in Figure 9.2. Given the x-andy-coordinates of the wells, how should the professor pick the optimal location of the main pipeline, which would be the one that minimizes the total length of the spurs? Show how to determine the optimal location in linear time. Problems 9-1 Largest i numbers in sorted order Given a set of n numbers, we wish to ﬁnd the i largest in sorted order using a comparison-based algorithm. Find the algorithm that implements each of the fol- lowing methods with the best asymptotic worst-case running time, and analyze the running times of the algorithms in terms of n and i. a. Sort the numbers, and list the i largest. b. Build a max-priority queue from the numbers, and call EXTRACT-MAX i times. c. Use an order-statistic algorithm to ﬁnd the ith largest number, partition around that number, and sort the i largest numbers.Problems for Chapter 9 225 9-2 Weighted median For n distinct elements x1;x2;:::;xn with positive weights w1;w2;:::;wn such that Pn iD1 wi D 1,theweighted (lower) median is the element xk satisfying X xi xk wi 1 2 : For example, if the elements are 0:1; 0:35; 0:05; 0:1; 0:15; 0:05; 0:2 and each ele- ment equals its weight (that is, wi D xi for i D 1;2;:::;7), then the median is 0:1, but the weighted median is 0:2. a. Argue that the median of x1;x2;:::;xn is the weighted median of the xi with weights wi D 1=n for i D 1;2;:::;n. b. Show how to compute the weighted median of n elements in O.nlg n/ worst- case time using sorting. c. Show how to compute the weighted median in ‚.n/ worst-case time using a linear-time median algorithm such as SELECT from Section 9.3. The post-ofﬁce location problem is deﬁned as follows. We are given n points p1;p2;:::;pn with associated weights w1;w2;:::;wn. We wish to ﬁnd a point p (not necessarily one of the input points) that minimizes the sum Pn iD1 wi d.p;pi /, where d.a;b/ is the distance between points a and b. d. Argue that the weighted median is a best solution for the 1-dimensional post- ofﬁce location problem, in which points are simply real numbers and the dis- tance between points a and b is d.a;b/ D ja bj. e. Find the best solution for the 2-dimensional post-ofﬁce location problem, in which the points are .x; y/ coordinate pairs and the distance between points a D .x1;y1/ and b D .x2;y2/ is the Manhattan distance given by d.a;b/ D jx1 x2j C jy1 y2j. 9-3 Small order statistics We showed that the worst-case number T .n/ of comparisons used by SELECT to select the ith order statistic from n numbers satisﬁes T .n/ D ‚.n/,butthe constant hidden by the ‚-notation is rather large. When i is small relative to n,we can implement a different procedure that uses SELECT as a subroutine but makes fewer comparisons in the worst case.226 Chapter 9 Medians and Order Statistics a. Describe an algorithm that uses Ui .n/ comparisons to ﬁnd the ith smallest of n elements, where Ui .n/ D ( T .n/ if i n=2 ; bn=2c C Ui .dn=2e/ C T.2i/ otherwise : (Hint: Begin with bn=2c disjoint pairwise comparisons, and recurse on the set containing the smaller element from each pair.) b. Show that, if i k 10 return NIL 11 else return i If we ignore lines 3–7 of the procedure, we have an ordinary algorithm for searching a sorted linked list, in which index i points to each position of the list in 1Because we have deﬁned a mergeable heap to support MINIMUM and EXTRACT-MIN, we can also refer to it as a mergeable min-heap. Alternatively, if it supported MAXIMUM and EXTRACT-MAX, it would be a mergeable max-heap.Problems for Chapter 10 251 turn. The search terminates once the index i “falls off” the end of the list or once keyŒi k. In the latter case, if keyŒi D k, clearly we have found a key with the value k. If, however, keyŒi > k, then we will never ﬁnd a key with the value k, and so terminating the search was the right thing to do. Lines 3–7 attempt to skip ahead to a randomly chosen position j .Suchaskip beneﬁts us if keyŒj is larger than keyŒi andnolargerthank; in such a case, j marks a position in the list that i would have to reach during an ordinary list search. Because the list is compact, we know that any choice of j between 1 and n indexes some object in the list rather than a slot on the free list. Instead of analyzing the performance of COMPACT-LIST-SEARCH directly, we shall analyze a related algorithm, COMPACT-LIST-SEARCH0, which executes two separate loops. This algorithm takes an additional parameter t which determines an upper bound on the number of iterations of the ﬁrst loop. COMPACT-LIST-SEARCH0 .L;n;k;t/ 1 i D L 2 for q D 1 to t 3 j D RANDOM.1; n/ 4 if keyŒi < keyŒj and keyŒj k 5 i D j 6 if keyŒi == k 7 return i 8 while i ¤ NIL and keyŒi < k 9 i D nextŒi 10 if i == NIL or keyŒi > k 11 return NIL 12 else return i To compare the execution of the algorithms COMPACT-LIST-SEARCH.L;n;k/ and COMPACT-LIST-SEARCH0.L;n;k;t/, assume that the sequence of integers re- turned by the calls of RANDOM.1; n/ is the same for both algorithms. a. Suppose that COMPACT-LIST-SEARCH.L;n;k/takes t iterations of the while loop of lines 2–8. Argue that COMPACT-LIST-SEARCH0.L;n;k;t/returns the same answer and that the total number of iterations of both the for and while loops within COMPACT-LIST-SEARCH0 is at least t. In the call COMPACT-LIST-SEARCH0.L;n;k;t/,letXt be the random variable that describes the distance in the linked list (that is, through the chain of next pointers) from position i to the desired key k after t iterations of the for loop of lines 2–7 have occurred.252 Chapter 10 Elementary Data Structures b. Argue that the expected running time of COMPACT-LIST-SEARCH0.L;n;k;t/ is O.t C E ŒXt /. c. Show that E ŒXt Pn rD1.1 r=n/t .(Hint: Use equation (C.25).) d. Show that Pn1 rD0 rt ntC1=.t C 1/. e. Prove that E ŒXt n=.t C 1/. f. Show that COMPACT-LIST-SEARCH0.L;n;k;t/ runs in O.t C n=t/ expected time. g. Conclude that COMPACT-LIST-SEARCH runs in O.pn/ expected time. h. Why do we assume that all keys are distinct in COMPACT-LIST-SEARCH?Ar- gue that random skips do not necessarily help asymptotically when the list con- tains repeated key values. Chapter notes Aho, Hopcroft, and Ullman [6] and Knuth [209] are excellent references for ele- mentary data structures. Many other texts cover both basic data structures and their implementation in a particular programming language. Examples of these types of textbooks include Goodrich and Tamassia [147], Main [241], Shaffer [311], and Weiss [352, 353, 354]. Gonnet [145] provides experimental data on the perfor- mance of many data-structure operations. The origin of stacks and queues as data structures in computer science is un- clear, since corresponding notions already existed in mathematics and paper-based business practices before the introduction of digital computers. Knuth [209] cites A. M. Turing for the development of stacks for subroutine linkage in 1947. Pointer-based data structures also seem to be a folk invention. According to Knuth, pointers were apparently used in early computers with drum memories. The A-1 language developed by G. M. Hopper in 1951 represented algebraic formulas as binary trees. Knuth credits the IPL-II language, developed in 1956 by A. Newell, J. C. Shaw, and H. A. Simon, for recognizing the importance and promoting the use of pointers. Their IPL-III language, developed in 1957, included explicit stack operations.11 Hash Tables Many applications require a dynamic set that supports only the dictionary opera- tions INSERT,SEARCH,andDELETE. For example, a compiler that translates a programming language maintains a symbol table, in which the keys of elements are arbitrary character strings corresponding to identiﬁers in the language. A hash table is an effective data structure for implementing dictionaries. Although search- ing for an element in a hash table can take as long as searching for an element in a linked list—‚.n/ time in the worst case—in practice, hashing performs extremely well. Under reasonable assumptions, the average time to search for an element in a hash table is O.1/. A hash table generalizes the simpler notion of an ordinary array. Directly ad- dressing into an ordinary array makes effective use of our ability to examine an arbitrary position in an array in O.1/ time. Section 11.1 discusses direct address- ing in more detail. We can take advantage of direct addressing when we can afford to allocate an array that has one position for every possible key. When the number of keys actually stored is small relative to the total number of possible keys, hash tables become an effective alternative to directly addressing an array, since a hash table typically uses an array of size proportional to the number of keys actually stored. Instead of using the key as an array index directly, the array index is computed from the key. Section 11.2 presents the main ideas, focusing on “chaining” as a way to handle “collisions,” in which more than one key maps to the same array index. Section 11.3 describes how we can compute array indices from keys using hash functions. We present and analyze several variations on the basic theme. Section 11.4 looks at “open addressing,” which is another way to deal with collisions. The bottom line is that hashing is an extremely effective and practical technique: the basic dictionary operations require only O.1/ time on the average. Section 11.5 explains how “perfect hashing” can support searches in O.1/ worst- case time, when the set of keys being stored is static (that is, when the set of keys never changes once stored).254 Chapter 11 Hash Tables 11.1 Direct-address tables Direct addressing is a simple technique that works well when the universe U of keys is reasonably small. Suppose that an application needs a dynamic set in which each element has a key drawn from the universe U D f0; 1; : : : ; m 1g,wherem is not too large. We shall assume that no two elements have the same key. To represent the dynamic set, we use an array, or direct-address table, denoted by TŒ0::m 1, in which each position, or slot, corresponds to a key in the uni- verse U . Figure 11.1 illustrates the approach; slot k points to an element in the set with key k. If the set contains no element with key k,thenTŒkD NIL. The dictionary operations are trivial to implement: DIRECT-ADDRESS-SEARCH.T; k/ 1 return TŒk DIRECT-ADDRESS-INSERT.T; x/ 1 TŒx:key D x DIRECT-ADDRESS-DELETE.T; x/ 1 TŒx:key D NIL Each of these operations takes only O.1/ time. T U (universe of keys) K (actual keys) 2 3 5 8 1 9 4 0 7 6 2 3 5 8 key satellite data 2 0 1 3 4 5 6 7 8 9 Figure 11.1 How to implement a dynamic set by a direct-address table T . Each key in the universe U D f0; 1; : : : ; 9g corresponds to an index in the table. The set K D f2; 3; 5; 8g of actual keys determines the slots in the table that contain pointers to elements. The other slots, heavily shaded, contain NIL.11.1 Direct-address tables 255 For some applications, the direct-address table itself can hold the elements in the dynamic set. That is, rather than storing an element’s key and satellite data in an object external to the direct-address table, with a pointer from a slot in the table to the object, we can store the object in the slot itself, thus saving space. We would use a special key within an object to indicate an empty slot. Moreover, it is often unnecessary to store the key of the object, since if we have the index of an object in the table, we have its key. If keys are not stored, however, we must have some way to tell whether the slot is empty. Exercises 11.1-1 Suppose that a dynamic set S is represented by a direct-address table T of length m. Describe a procedure that ﬁnds the maximum element of S. What is the worst-case performance of your procedure? 11.1-2 A bit vector is simply an array of bits (0sand1s). A bit vector of length m takes much less space than an array of m pointers. Describe how to use a bit vector to represent a dynamic set of distinct elements with no satellite data. Dictionary operations should run in O.1/ time. 11.1-3 Suggest how to implement a direct-address table in which the keys of stored el- ements do not need to be distinct and the elements can have satellite data. All three dictionary operations (INSERT,DELETE,andSEARCH) should run in O.1/ time. (Don’t forget that DELETE takes as an argument a pointer to an object to be deleted, not a key.) 11.1-4 ? We wish to implement a dictionary by using direct addressing on a huge array. At the start, the array entries may contain garbage, and initializing the entire array is impractical because of its size. Describe a scheme for implementing a direct- address dictionary on a huge array. Each stored object should use O.1/ space; the operations SEARCH,INSERT,andDELETE should take O.1/ time each; and initializing the data structure should take O.1/ time. (Hint: Use an additional array, treated somewhat like a stack whose size is the number of keys actually stored in the dictionary, to help determine whether a given entry in the huge array is valid or not.)256 Chapter 11 Hash Tables 11.2 Hash tables The downside of direct addressing is obvious: if the universe U is large, storing atableT of size jU j may be impractical, or even impossible, given the memory available on a typical computer. Furthermore, the set K of keys actually stored may be so small relative to U that most of the space allocated for T would be wasted. When the set K of keys stored in a dictionary is much smaller than the uni- verse U of all possible keys, a hash table requires much less storage than a direct- address table. Speciﬁcally, we can reduce the storage requirement to ‚.jKj/ while we maintain the beneﬁt that searching for an element in the hash table still requires only O.1/ time. The catch is that this bound is for the average-case time, whereas for direct addressing it holds for the worst-case time. With direct addressing, an element with key k is stored in slot k. With hashing, this element is stored in slot h.k/; that is, we use a hash function h to compute the slot from the key k. Here, h maps the universe U of keys into the slots of a hash table TŒ0::m 1: h W U ! f0; 1; : : : ; m 1g ; where the size m of the hash table is typically much less than jU j. We say that an element with key k hashes to slot h.k/; we also say that h.k/ is the hash value of key k. Figure 11.2 illustrates the basic idea. The hash function reduces the range of array indices and hence the size of the array. Instead of a size of jU j, the array can have size m. T U (universe of keys) K (actual keys) 0 m–1 k1 k2 k3 k4 k5 h(k1) h(k4) h(k3) h(k2) = h(k5) Figure 11.2 Using a hash function h to map keys to hash-table slots. Because keys k2 and k5 map to the same slot, they collide.11.2 Hash tables 257 T U (universe of keys) K (actual keys) k1 k2 k3 k4 k5 k6 k7 k8 k1 k2 k3 k4 k5 k6 k7 k8 Figure 11.3 Collision resolution by chaining. Each hash-table slot TŒjcontains a linked list of all the keys whose hash value is j. For example, h.k1/ D h.k4/ and h.k5/ D h.k7/ D h.k2/. The linked list can be either singly or doubly linked; we show it as doubly linked because deletion is faster that way. There is one hitch: two keys may hash to the same slot. We call this situation a collision. Fortunately, we have effective techniques for resolving the conﬂict created by collisions. Of course, the ideal solution would be to avoid collisions altogether. We might try to achieve this goal by choosing a suitable hash function h. One idea is to make h appear to be “random,” thus avoiding collisions or at least minimizing their number. The very term “to hash,” evoking images of random mixing and chopping, captures the spirit of this approach. (Of course, a hash function h must be deterministic in that a given input k should always produce the same output h.k/.) Because jU j >m, however, there must be at least two keys that have the same hash value; avoiding collisions altogether is therefore impossible. Thus, while a well- designed, “random”-looking hash function can minimize the number of collisions, we still need a method for resolving the collisions that do occur. The remainder of this section presents the simplest collision resolution tech- nique, called chaining. Section 11.4 introduces an alternative method for resolving collisions, called open addressing. Collision resolution by chaining In chaining, we place all the elements that hash to the same slot into the same linked list, as Figure 11.3 shows. Slot j contains a pointer to the head of the list of all stored elements that hash to j ; if there are no such elements, slot j contains NIL.258 Chapter 11 Hash Tables The dictionary operations on a hash table T are easy to implement when colli- sions are resolved by chaining: CHAINED-HASH-INSERT.T; x/ 1 insert x at the head of list TŒh.x:key/ CHAINED-HASH-SEARCH.T; k/ 1 search for an element with key k in list TŒh.k/ CHAINED-HASH-DELETE.T; x/ 1 delete x from the list TŒh.x:key/ The worst-case running time for insertion is O.1/. The insertion procedure is fast in part because it assumes that the element x being inserted is not already present in the table; if necessary, we can check this assumption (at additional cost) by search- ing for an element whose key is x:key before we insert. For searching, the worst- case running time is proportional to the length of the list; we shall analyze this operation more closely below. We can delete an element in O.1/ time if the lists are doubly linked, as Figure 11.3 depicts. (Note that CHAINED-HASH-DELETE takes as input an element x and not its key k, so that we don’t have to search for x ﬁrst. If the hash table supports deletion, then its linked lists should be doubly linked so that we can delete an item quickly. If the lists were only singly linked, then to delete element x, we would ﬁrst have to ﬁnd x in the list TŒh.x:key/ so that we could update the next attribute of x’s predecessor. With singly linked lists, both deletion and searching would have the same asymptotic running times.) Analysis of hashing with chaining How well does hashing with chaining perform? In particular, how long does it take to search for an element with a given key? Given a hash table T with m slots that stores n elements, we deﬁne the load factor ˛ for T as n=m, that is, the average number of elements stored in a chain. Our analysis will be in terms of ˛, which can be less than, equal to, or greater than 1. The worst-case behavior of hashing with chaining is terrible: all n keys hash to the same slot, creating a list of length n. The worst-case time for searching is thus ‚.n/ plus the time to compute the hash function—no better than if we used one linked list for all the elements. Clearly, we do not use hash tables for their worst-case performance. (Perfect hashing, described in Section 11.5, does provide good worst-case performance when the set of keys is static, however.) The average-case performance of hashing depends on how well the hash func- tion h distributes the set of keys to be stored among the m slots, on the average.11.2 Hash tables 259 Section 11.3 discusses these issues, but for now we shall assume that any given element is equally likely to hash into any of the m slots, independently of where any other element has hashed to. We call this the assumption of simple uniform hashing. For j D 0; 1; : : : ; m 1, let us denote the length of the list TŒjby nj ,sothat n D n0 C n1 CCnm1 ; (11.1) and the expected value of nj is E Œnj D ˛ D n=m. We assume that O.1/ time sufﬁces to compute the hash value h.k/,sothat the time required to search for an element with key k depends linearly on the length nh.k/ of the list TŒh.k/. Setting aside the O.1/ time required to compute the hash function and to access slot h.k/, let us consider the expected number of elements examined by the search algorithm, that is, the number of elements in the list TŒh.k/that the algorithm checks to see whether any have a key equal to k.We shall consider two cases. In the ﬁrst, the search is unsuccessful: no element in the table has key k. In the second, the search successfully ﬁnds an element with key k. Theorem 11.1 In a hash table in which collisions are resolved by chaining, an unsuccessful search takes average-case time ‚.1C˛/, under the assumption of simple uniform hashing. Proof Under the assumption of simple uniform hashing, any key k not already stored in the table is equally likely to hash to any of the m slots. The expected time to search unsuccessfully for a key k is the expected time to search to the end of list TŒh.k/, which has expected length E Œnh.k/ D ˛. Thus, the expected number of elements examined in an unsuccessful search is ˛, and the total time required (including the time for computing h.k/)is‚.1 C ˛/. The situation for a successful search is slightly different, since each list is not equally likely to be searched. Instead, the probability that a list is searched is pro- portional to the number of elements it contains. Nonetheless, the expected search time still turns out to be ‚.1 C ˛/. Theorem 11.2 In a hash table in which collisions are resolved by chaining, a successful search takes average-case time ‚.1C˛/, under the assumption of simple uniform hashing. Proof We assume that the element being searched for is equally likely to be any of the n elements stored in the table. The number of elements examined during a successful search for an element x is one more than the number of elements that260 Chapter 11 Hash Tables appear before x in x’s list. Because new elements are placed at the front of the list, elements before x in the list were all inserted after x was inserted. To ﬁnd the expected number of elements examined, we take the average, over the n ele- ments x in the table, of 1 plus the expected number of elements added to x’s list after x was added to the list. Let xi denote the ith element inserted into the ta- ble, for i D 1;2;:::;n,andletki D xi :key. For keys ki and kj ,wedeﬁnethe indicator random variable Xij D I fh.ki / D h.kj /g. Under the assumption of sim- ple uniform hashing, we have Pr fh.ki / D h.kj /g D 1=m, and so by Lemma 5.1, E ŒXij D 1=m. Thus, the expected number of elements examined in a successful search is E " 1 n nX iD1 1 C nX jDiC1 Xij !# D 1 n nX iD1 1 C nX jDiC1 E ŒXij ! (by linearity of expectation) D 1 n nX iD1 1 C nX jDiC1 1 m ! D 1 C 1 nm nX iD1 .n i/ D 1 C 1 nm nX iD1 n nX iD1 i ! D 1 C 1 nm n2 n.n C 1/ 2 (by equation (A.1)) D 1 C n 1 2m D 1 C ˛ 2 ˛ 2n : Thus, the total time required for a successful search (including the time for com- puting the hash function) is ‚.2 C ˛=2 ˛=2n/ D ‚.1 C ˛/. What does this analysis mean? If the number of hash-table slots is at least pro- portional to the number of elements in the table, we have n D O.m/ and, con- sequently, ˛ D n=m D O.m/=m D O.1/. Thus, searching takes constant time on average. Since insertion takes O.1/ worst-case time and deletion takes O.1/ worst-case time when the lists are doubly linked, we can support all dictionary operations in O.1/ time on average.11.2 Hash tables 261 Exercises 11.2-1 Suppose we use a hash function h to hash n distinct keys into an array T of length m. Assuming simple uniform hashing, what is the expected number of collisions? More precisely, what is the expected cardinality of ffk; lg W k ¤ l and h.k/ D h.l/g? 11.2-2 Demonstrate what happens when we insert the keys 5; 28; 19; 15; 20; 33; 12; 17; 10 into a hash table with collisions resolved by chaining. Let the table have 9 slots, and let the hash function be h.k/ D k mod 9. 11.2-3 Professor Marley hypothesizes that he can obtain substantial performance gains by modifying the chaining scheme to keep each list in sorted order. How does the pro- fessor’s modiﬁcation affect the running time for successful searches, unsuccessful searches, insertions, and deletions? 11.2-4 Suggest how to allocate and deallocate storage for elements within the hash table itself by linking all unused slots into a free list. Assume that one slot can store a ﬂag and either one element plus a pointer or two pointers. All dictionary and free-list operations should run in O.1/ expected time. Does the free list need to be doubly linked, or does a singly linked free list sufﬁce? 11.2-5 Suppose that we are storing a set of n keys into a hash table of size m. Show that if the keys are drawn from a universe U with jU j >nm,thenU has a subset of size n consisting of keys that all hash to the same slot, so that the worst-case searching time for hashing with chaining is ‚.n/. 11.2-6 Suppose we have stored n keys in a hash table of size m, with collisions resolved by chaining, and that we know the length of each chain, including the length L of the longest chain. Describe a procedure that selects a key uniformly at random from among the keys in the hash table and returns it in expected time O.L .1 C 1=˛//.262 Chapter 11 Hash Tables 11.3 Hash functions In this section, we discuss some issues regarding the design of good hash functions and then present three schemes for their creation. Two of the schemes, hashing by division and hashing by multiplication, are heuristic in nature, whereas the third scheme, universal hashing, uses randomization to provide provably good perfor- mance. What makes a good hash function? A good hash function satisﬁes (approximately) the assumption of simple uniform hashing: each key is equally likely to hash to any of the m slots, independently of where any other key has hashed to. Unfortunately, we typically have no way to check this condition, since we rarely know the probability distribution from which the keys are drawn. Moreover, the keys might not be drawn independently. Occasionally we do know the distribution. For example, if we know that the keys are random real numbers k independently and uniformly distributed in the range 0 k<1, then the hash function h.k/ D bkmc satisﬁes the condition of simple uniform hashing. In practice, we can often employ heuristic techniques to create a hash function that performs well. Qualitative information about the distribution of keys may be useful in this design process. For example, consider a compiler’s symbol table, in which the keys are character strings representing identiﬁers in a program. Closely related symbols, such as pt and pts, often occur in the same program. A good hash function would minimize the chance that such variants hash to the same slot. A good approach derives the hash value in a way that we expect to be indepen- dent of any patterns that might exist in the data. For example, the “division method” (discussed in Section 11.3.1) computes the hash value as the remainder when the key is divided by a speciﬁed prime number. This method frequently gives good results, assuming that we choose a prime number that is unrelated to any patterns in the distribution of keys. Finally, we note that some applications of hash functions might require stronger properties than are provided by simple uniform hashing. For example, we might want keys that are “close” in some sense to yield hash values that are far apart. (This property is especially desirable when we are using linear probing, deﬁned in Section 11.4.) Universal hashing, described in Section 11.3.3, often provides the desired properties.11.3 Hash functions 263 Interpreting keys as natural numbers Most hash functions assume that the universe of keys is the set N D f0; 1; 2; : : :g of natural numbers. Thus, if the keys are not natural numbers, we ﬁnd a way to interpret them as natural numbers. For example, we can interpret a character string as an integer expressed in suitable radix notation. Thus, we might interpret the identiﬁer pt as the pair of decimal integers .112; 116/,sincep D 112 and t D 116 in the ASCII character set; then, expressed as a radix-128 integer, pt becomes .112 128/ C 116 D 14452. In the context of a given application, we can usually devise some such method for interpreting each key as a (possibly large) natural number. In what follows, we assume that the keys are natural numbers. 11.3.1 The division method In the division method for creating hash functions, we map a key k into one of m slots by taking the remainder of k divided by m. That is, the hash function is h.k/ D k mod m: For example, if the hash table has size m D 12 and the key is k D 100,then h.k/ D 4. Since it requires only a single division operation, hashing by division is quite fast. When using the division method, we usually avoid certain values of m.For example, m should not be a power of 2, since if m D 2p,thenh.k/ is just the p lowest-order bits of k. Unless we know that all low-order p-bit patterns are equally likely, we are better off designing the hash function to depend on all the bits of the key. As Exercise 11.3-3 asks you to show, choosing m D 2p 1 when k is a character string interpreted in radix 2p may be a poor choice, because permuting the characters of k does not change its hash value. A prime not too close to an exact power of 2 is often a good choice for m.For example, suppose we wish to allocate a hash table, with collisions resolved by chaining, to hold roughly n D 2000 character strings, where a character has 8 bits. We don’t mind examining an average of 3 elements in an unsuccessful search, and so we allocate a hash table of size m D 701. We could choose m D 701 because it is a prime near 2000=3 but not near any power of 2. Treating each key k as an integer, our hash function would be h.k/ D k mod 701 : 11.3.2 The multiplication method The multiplication method for creating hash functions operates in two steps. First, we multiply the key k by a constant A in the range 0m. We now deﬁne the hash function hab for any a 2 Z p and any b 2 Zp using a linear transformation followed by reductions modulo p and then modulo m: hab.k/ D ..ak C b/ mod p/ mod m: (11.3) For example, with p D 17 and m D 6,wehaveh3;4.8/ D 5. The family of all such hash functions is Hpm D ˚ hab W a 2 Z p and b 2 Zp : (11.4) Each hash function hab maps Zp to Zm. This class of hash functions has the nice property that the size m of the output range is arbitrary—not necessarily prime—a feature which we shall use in Section 11.5. Since we have p 1 choices for a and p choices for b, the collection Hpm contains p.p 1/ hash functions. Theorem 11.5 The class Hpm of hash functions deﬁned by equations (11.3) and (11.4) is universal. Proof Consider two distinct keys k and l from Zp,sothatk ¤ l.Foragiven hash function hab we let r D .ak C b/ mod p; s D .al C b/ mod p: We ﬁrst note that r ¤ s. Why? Observe that r s a.k l/ .mod p/ : It follows that r ¤ s because p is prime and both a and .k l/ are nonzero modulo p, and so their product must also be nonzero modulo p by Theorem 31.6. Therefore, when computing any hab 2 Hpm, distinct inputs k and l map to distinct268 Chapter 11 Hash Tables values r and s modulo p; there are no collisions yet at the “mod p level.” Moreover, each of the possible p.p1/ choices for the pair .a; b/ with a ¤ 0 yields a different resulting pair .r; s/ with r ¤ s, since we can solve for a and b given r and s: a D .r s/..k l/1 mod p/ mod p; b D .r ak/ mod p; where ..k l/1 mod p/ denotes the unique multiplicative inverse, modulo p, of k l. Since there are only p.p 1/ possible pairs .r; s/ with r ¤ s,there is a one-to-one correspondence between pairs .a; b/ with a ¤ 0 and pairs .r; s/ with r ¤ s. Thus, for any given pair of inputs k and l,ifwepick.a; b/ uniformly at random from Z p Zp, the resulting pair .r; s/ is equally likely to be any pair of distinct values modulo p. Therefore, the probability that distinct keys k and l collide is equal to the prob- ability that r s.mod m/ when r and s are randomly chosen as distinct values modulo p.Foragivenvalueofr,ofthep 1 possible remaining values for s,the number of values s such that s ¤ r and s r.mod m/ is at most dp=me 1 ..p C m 1/=m/ 1 (by inequality (3.6)) D .p 1/=m : The probability that s collides with r when reduced modulo m is at most ..p 1/=m/=.p 1/ D 1=m. Therefore, for any pair of distinct values k; l 2 Zp, Pr fhab.k/ D hab.l/g 1=m ; so that Hpm is indeed universal. Exercises 11.3-1 Suppose we wish to search a linked list of length n, where each element contains akeyk along with a hash value h.k/. Each key is a long character string. How might we take advantage of the hash values when searching the list for an element with a given key? 11.3-2 Suppose that we hash a string of r characters into m slots by treating it as a radix-128 number and then using the division method. We can easily represent the number m as a 32-bit computer word, but the string of r characters, treated as a radix-128 number, takes many words. How can we apply the division method to compute the hash value of the character string without using more than a constant number of words of storage outside the string itself?11.4 Open addressing 269 11.3-3 Consider a version of the division method in which h.k/ D k mod m,where m D 2p 1 and k is a character string interpreted in radix 2p. Show that if we can derive string x from string y by permuting its characters, then x and y hash to the same value. Give an example of an application in which this property would be undesirable in a hash function. 11.3-4 Consider a hash table of size m D 1000 and a corresponding hash function h.k/ D bm.kAmod 1/c for A D . p 5 1/=2. Compute the locations to which the keys 61, 62, 63, 64,and65 are mapped. 11.3-5 ? DeﬁneafamilyH of hash functions from a ﬁnite set U to a ﬁnite set B to be -universal if for all pairs of distinct elements k and l in U , Pr fh.k/ D h.l/g ; where the probability is over the choice of the hash function h drawn at random from the family H. Show that an -universal family of hash functions must have 1 jBj 1 jU j : 11.3-6 ? Let U be the set of n-tuples of values drawn from Zp,andletB D Zp,wherep is prime. Deﬁne the hash function hb W U ! B for b 2 Zp on an input n-tuple ha0;a1;:::;an1i from U as hb.ha0;a1;:::;an1i/ D n1X jD0 aj bj ! mod p; and let H D fhb W b 2 Zpg. Argue that H is ..n 1/=p/-universal according to the deﬁnition of -universal in Exercise 11.3-5. (Hint: See Exercise 31.4-4.) 11.4 Open addressing In open addressing, all elements occupy the hash table itself. That is, each table entry contains either an element of the dynamic set or NIL. When searching for an element, we systematically examine table slots until either we ﬁnd the desired element or we have ascertained that the element is not in the table. No lists and270 Chapter 11 Hash Tables no elements are stored outside the table, unlike in chaining. Thus, in open ad- dressing, the hash table can “ﬁll up” so that no further insertions can be made; one consequence is that the load factor ˛ can never exceed 1. Of course, we could store the linked lists for chaining inside the hash table, in the otherwise unused hash-table slots (see Exercise 11.2-4), but the advantage of open addressing is that it avoids pointers altogether. Instead of following pointers, we compute the sequence of slots to be examined. The extra memory freed by not storing pointers provides the hash table with a larger number of slots for the same amount of memory, potentially yielding fewer collisions and faster retrieval. To perform insertion using open addressing, we successively examine, or probe, the hash table until we ﬁnd an empty slot in which to put the key. Instead of being ﬁxed in the order 0; 1; : : : ; m 1 (which requires ‚.n/ search time), the sequence of positions probed depends upon the key being inserted. To determine which slots to probe, we extend the hash function to include the probe number (starting from 0) as a second input. Thus, the hash function becomes h W U f0; 1; : : : ; m 1g ! f0; 1; : : : ; m 1g : With open addressing, we require that for every key k,theprobe sequence hh.k;0/;h.k;1/;:::;h.k;m 1/i be a permutation of h0; 1; : : : ; m1i, so that every hash-table position is eventually considered as a slot for a new key as the table ﬁlls up. In the following pseudocode, we assume that the elements in the hash table T are keys with no satellite infor- mation; the key k is identical to the element containing key k. Each slot contains either a key or NIL (if the slot is empty). The HASH-INSERT procedure takes as input a hash table T and a key k. It either returns the slot number where it stores key k or ﬂags an error because the hash table is already full. HASH-INSERT.T; k/ 1 i D 0 2 repeat 3 j D h.k; i/ 4 if TŒj== NIL 5 TŒj D k 6 return j 7 else i D i C 1 8 until i == m 9 error “hash table overﬂow” The algorithm for searching for key k probes the same sequence of slots that the insertion algorithm examined when key k was inserted. Therefore, the search can11.4 Open addressing 271 terminate (unsuccessfully) when it ﬁnds an empty slot, since k would have been inserted there and not later in its probe sequence. (This argument assumes that keys are not deleted from the hash table.) The procedure HASH-SEARCH takes as input a hash table T and a key k, returning j if it ﬁnds that slot j contains key k,orNIL if key k is not present in table T . HASH-SEARCH.T; k/ 1 i D 0 2 repeat 3 j D h.k; i/ 4 if TŒj== k 5 return j 6 i D i C 1 7 until TŒj== NIL or i == m 8 return NIL Deletion from an open-address hash table is difﬁcult. When we delete a key from slot i, we cannot simply mark that slot as empty by storing NIL in it. If we did, we might be unable to retrieve any key k during whose insertion we had probed slot i and found it occupied. We can solve this problem by marking the slot, storing in it the special value DELETED instead of NIL. We would then modify the procedure HASH-INSERT to treat such a slot as if it were empty so that we can insert a new key there. We do not need to modify HASH-SEARCH, since it will pass over DELETED values while searching. When we use the special value DELETED, however, search times no longer depend on the load factor ˛, and for this reason chaining is more commonly selected as a collision resolution technique when keys must be deleted. In our analysis, we assume uniform hashing: the probe sequence of each key is equally likely to be any of the mŠ permutations of h0;1;:::; m 1i.Uni- form hashing generalizes the notion of simple uniform hashing deﬁned earlier to a hash function that produces not just a single number, but a whole probe sequence. True uniform hashing is difﬁcult to implement, however, and in practice suitable approximations (such as double hashing, deﬁned below) are used. We will examine three commonly used techniques to compute the probe se- quences required for open addressing: linear probing, quadratic probing, and dou- ble hashing. These techniques all guarantee that hh.k;0/;h.k;1/;:::;h.k;m 1/i is a permutation of h0;1;:::;m 1i for each key k. None of these techniques ful- ﬁlls the assumption of uniform hashing, however, since none of them is capable of generating more than m2 different probe sequences (instead of the mŠ that uniform hashing requires). Double hashing has the greatest number of probe sequences and, as one might expect, seems to give the best results.272 Chapter 11 Hash Tables Linear probing Given an ordinary hash function h0 W U ! f0; 1; : : : ; m 1g, which we refer to as an auxiliary hash function, the method of linear probing uses the hash function h.k; i/ D .h0.k/ C i/ mod m for i D 0; 1; : : : ; m 1.Givenkeyk, we ﬁrst probe TŒh0.k/, i.e., the slot given by the auxiliary hash function. We next probe slot TŒh0.k/ C 1, and so on up to slot TŒm 1. Then we wrap around to slots T Œ0; T Œ1; : : : until we ﬁnally probe slot TŒh0.k/ 1. Because the initial probe determines the entire probe sequence, there are only m distinct probe sequences. Linear probing is easy to implement, but it suffers from a problem known as primary clustering. Long runs of occupied slots build up, increasing the average search time. Clusters arise because an empty slot preceded by i full slots gets ﬁlled next with probability .i C 1/=m. Long runs of occupied slots tend to get longer, and the average search time increases. Quadratic probing Quadratic probing uses a hash function of the form h.k; i/ D .h0.k/ C c1i C c2i 2/ mod m; (11.5) where h0 is an auxiliary hash function, c1 and c2 are positive auxiliary constants, and i D 0; 1; : : : ; m 1. The initial position probed is TŒh0.k/; later positions probed are offset by amounts that depend in a quadratic manner on the probe num- ber i. This method works much better than linear probing, but to make full use of the hash table, the values of c1, c2,andm are constrained. Problem 11-3 shows one way to select these parameters. Also, if two keys have the same initial probe position, then their probe sequences are the same, since h.k1;0/ D h.k2;0/ im- plies h.k1;i/D h.k2;i/. This property leads to a milder form of clustering, called secondary clustering. As in linear probing, the initial probe determines the entire sequence, and so only m distinct probe sequences are used. Double hashing Double hashing offers one of the best methods available for open addressing be- cause the permutations produced have many of the characteristics of randomly chosen permutations. Double hashing uses a hash function of the form h.k; i/ D .h1.k/ C ih2.k// mod m; where both h1 and h2 are auxiliary hash functions. The initial probe goes to posi- tion TŒh1.k/; successive probe positions are offset from previous positions by the11.4 Open addressing 273 0 1 2 3 4 5 6 7 8 9 10 11 12 79 69 98 72 14 50 Figure 11.5 Insertion by double hashing. Here we have a hash table of size 13 with h1.k/ D k mod 13 and h2.k/ D 1 C .k mod 11/.Since14 1.mod 13/ and 14 3.mod 11/,weinsert the key 14 into empty slot 9, after examining slots 1 and 5 and ﬁnding them to be occupied. amount h2.k/, modulo m. Thus, unlike the case of linear or quadratic probing, the probe sequence here depends in two ways upon the key k, since the initial probe position, the offset, or both, may vary. Figure 11.5 gives an example of insertion by double hashing. The value h2.k/ must be relatively prime to the hash-table size m for the entire hash table to be searched. (See Exercise 11.4-4.) A convenient way to ensure this condition is to let m be a power of 2 and to design h2 so that it always produces an odd number. Another way is to let m be prime and to design h2 so that it always returns a positive integer less than m. For example, we could choose m prime and let h1.k/ D k mod m; h2.k/ D 1 C .k mod m0/; where m0 is chosen to be slightly less than m (say, m 1). For example, if k D 123456, m D 701,andm0 D 700,wehaveh1.k/ D 80 and h2.k/ D 257,so that we ﬁrst probe position 80, and then we examine every 257th slot (modulo m) until we ﬁnd the key or have examined every slot. When m is prime or a power of 2, double hashing improves over linear or qua- dratic probing in that ‚.m2/ probe sequences are used, rather than ‚.m/,since each possible .h1.k/; h2.k// pair yields a distinct probe sequence. As a result, for274 Chapter 11 Hash Tables such values of m, the performance of double hashing appears to be very close to the performance of the “ideal” scheme of uniform hashing. Although values of m other than primes or powers of 2 could in principle be used with double hashing, in practice it becomes more difﬁcult to efﬁciently gen- erate h2.k/ in a way that ensures that it is relatively prime to m, in part because the relative density .m/=m of such numbers may be small (see equation (31.24)). Analysis of open-address hashing As in our analysis of chaining, we express our analysis of open addressing in terms of the load factor ˛ D n=m of the hash table. Of course, with open addressing, at most one element occupies each slot, and thus n m, which implies ˛ 1. We assume that we are using uniform hashing. In this idealized scheme, the probe sequence hh.k; 0/; h.k; 1/; : : : ; h.k; m 1/i used to insert or search for each key k is equally likely to be any permutation of h0; 1; : : : ; m 1i. Of course, a given key has a unique ﬁxed probe sequence associated with it; what we mean here is that, considering the probability distribution on the space of keys and the operation of the hash function on the keys, each possible probe sequence is equally likely. We now analyze the expected number of probes for hashing with open address- ing under the assumption of uniform hashing, beginning with an analysis of the number of probes made in an unsuccessful search. Theorem 11.6 Given an open-address hash table with load factor ˛ D n=m < 1, the expected number of probes in an unsuccessful search is at most 1=.1˛/, assuming uniform hashing. Proof In an unsuccessful search, every probe but the last accesses an occupied slot that does not contain the desired key, and the last slot probed is empty. Let us deﬁne the random variable X to be the number of probes made in an unsuccessful search, and let us also deﬁne the event Ai ,fori D 1;2;:::, to be the event that an ith probe occurs and it is to an occupied slot. Then the event fX ig is the intersection of events A1 \A2 \\Ai1. We will bound Pr fX ig by bounding Pr fA1 \ A2 \\Ai1g. By Exercise C.2-5, Pr fA1 \ A2 \\Ai1g D Pr fA1g Pr fA2 j A1g Pr fA3 j A1 \ A2g Pr fAi1 j A1 \ A2 \\Ai2g : Since there are n elements and m slots, Pr fA1g D n=m.Forj>1, the probability that there is a j th probe and it is to an occupied slot, given that the ﬁrst j 1 probes were to occupied slots, is .nj C1/=.mj C1/. This probability follows11.4 Open addressing 275 because we would be ﬁnding one of the remaining .n .j 1// elements in one of the .m .j 1// unexamined slots, and by the assumption of uniform hashing, the probability is the ratio of these quantities. Observing that n2lg ng D O.1=n2/. Let the random variable X D max1in Xi denote the maximum number of probes required by any of the n insertions. c. Show that Pr fX>2lg ng D O.1=n/. d. Show that the expected length E ŒX of the longest probe sequence is O.lg n/.Problems for Chapter 11 283 11-2 Slot-size bound for chaining Suppose that we have a hash table with n slots, with collisions resolved by chain- ing, and suppose that n keys are inserted into the table. Each key is equally likely to be hashed to each slot. Let M be the maximum number of keys in any slot after all the keys have been inserted. Your mission is to prove an O.lg n= lg lg n/ upper bound on E ŒM , the expected value of M. a. Argue that the probability Qk that exactly k keys hash to a particular slot is given by Qk D 1 n k 1 1 n nk n k ! : b. Let Pk be the probability that M D k, that is, the probability that the slot containing the most keys contains k keys. Show that Pk nQk. c. Use Stirling’s approximation, equation (3.18), to show that Qk 1such that Qk0 <1=n3 for k0 D c lg n= lg lg n. Conclude that Pk <1=n2 for k k0 D c lg n= lg lg n. e. Argue that E ŒM Pr M>c lg n lg lg n n C Pr M c lg n lg lg n c lg n lg lg n : Conclude that E ŒM D O.lg n= lg lg n/. 11-3 Quadratic probing Suppose that we are given a key k to search for in a hash table with positions 0; 1; : : : ; m1, and suppose that we have a hash function h mapping the key space into the set f0; 1; : : : ; m 1g. The search scheme is as follows: 1. Compute the value j D h.k/, and set i D 0. 2. Probe in position j for the desired key k. If you ﬁnd it, or if this position is empty, terminate the search. 3. Set i D i C 1.Ifi now equals m, the table is full, so terminate the search. Otherwise, set j D .i C j/mod m, and return to step 2. Assume that m isapowerof2. a. Show that this scheme is an instance of the general “quadratic probing” scheme by exhibiting the appropriate constants c1 and c2 for equation (11.5). b. Prove that this algorithm examines every table position in the worst case.284 Chapter 11 Hash Tables 11-4 Hashing and authentication Let H be a class of hash functions in which each hash function h 2 H maps the universe U of keys to f0; 1; : : : ; m 1g. We say that H is k-universal if, for every ﬁxed sequence of k distinct keys hx.1/;x.2/; :::; x.k/i and for any h chosen at random from H, the sequence hh.x.1//; h.x.2//; : : : ; h.x.k//i is equally likely to be any of the mk sequences of length k with elements drawn from f0; 1; : : : ; m 1g. a. Show that if the family H of hash functions is 2-universal, then it is universal. b. Suppose that the universe U is the set of n-tuples of values drawn from Zp D f0; 1; : : : ; p 1g,wherep is prime. Consider an element x D hx0;x1;:::;xn1i2U .Foranyn-tuple a Dha0;a1;:::;an1i2U ,de- ﬁne the hash function ha by ha.x/ D n1X jD0 aj xj ! mod p: Let H D fhag. Show that H is universal, but not 2-universal. (Hint: Find a key for which all hash functions in H produce the same value.) c. Suppose that we modify H slightly from part (b): for any a 2 U and for any b 2 Zp,deﬁne h0 ab.x/ D n1X jD0 aj xj C b ! mod p and H 0 D fh0 abg. Argue that H 0 is 2-universal. (Hint: Consider ﬁxed n-tuples x 2 U and y 2 U , with xi ¤ yi for some i. What happens to h0 ab.x/ and h0 ab.y/ as ai and b range over Zp?) d. Suppose that Alice and Bob secretly agree on a hash function h from a 2-universal family H of hash functions. Each h 2 H maps from a universe of keys U to Zp,wherep is prime. Later, Alice sends a message m to Bob over the Internet, where m 2 U . She authenticates this message to Bob by also sending an authentication tag t D h.m/, and Bob checks that the pair .m; t/ he receives indeed satisﬁes t D h.m/. Suppose that an adversary intercepts .m; t/ en route and tries to fool Bob by replacing the pair .m; t/ with a different pair .m0;t0/. Argue that the probability that the adversary succeeds in fooling Bob into ac- cepting .m0;t0/ is at most 1=p, no matter how much computing power the ad- versary has, and even if the adversary knows the family H of hash functions used.Notes for Chapter 11 285 Chapter notes Knuth [211] and Gonnet [145] are excellent references for the analysis of hash- ing algorithms. Knuth credits H. P. Luhn (1953) for inventing hash tables, along with the chaining method for resolving collisions. At about the same time, G. M. Amdahl originated the idea of open addressing. Carter and Wegman introduced the notion of universal classes of hash functions in 1979 [58]. Fredman, Koml´os, and Szemer´edi [112] developed the perfect hashing scheme for static sets presented in Section 11.5. An extension of their method to dynamic sets, handling insertions and deletions in amortized expected time O.1/, has been given by Dietzfelbinger et al. [86].12 Binary Search Trees The search tree data structure supports many dynamic-set operations, including SEARCH,MINIMUM,MAXIMUM,PREDECESSOR,SUCCESSOR,INSERT,and DELETE. Thus, we can use a search tree both as a dictionary and as a priority queue. Basic operations on a binary search tree take time proportional to the height of the tree. For a complete binary tree with n nodes, such operations run in ‚.lg n/ worst-case time. If the tree is a linear chain of n nodes, however, the same oper- ations take ‚.n/ worst-case time. We shall see in Section 12.4 that the expected height of a randomly built binary search tree is O.lg n/, so that basic dynamic-set operations on such a tree take ‚.lg n/ time on average. In practice, we can’t always guarantee that binary search trees are built ran- domly, but we can design variations of binary search trees with good guaranteed worst-case performance on basic operations. Chapter 13 presents one such vari- ation, red-black trees, which have height O.lg n/. Chapter 18 introduces B-trees, which are particularly good for maintaining databases on secondary (disk) storage. After presenting the basic properties of binary search trees, the following sec- tions show how to walk a binary search tree to print its values in sorted order, how to search for a value in a binary search tree, how to ﬁnd the minimum or maximum element, how to ﬁnd the predecessor or successor of an element, and how to insert into or delete from a binary search tree. The basic mathematical properties of trees appear in Appendix B. 12.1 What is a binary search tree? A binary search tree is organized, as the name suggests, in a binary tree, as shown in Figure 12.1. We can represent such a tree by a linked data structure in which each node is an object. In addition to a key and satellite data, each node contains attributes left, right,andp that point to the nodes corresponding to its left child,12.1 What is a binary search tree? 287 5 2 5 5 8 7 6 (a) 6 8 7 5 2 (b) Figure 12.1 Binary search trees. For any node x, the keys in the left subtree of x are at most x:key, and the keys in the right subtree of x are at least x:key. Different binary search trees can represent the same set of values. The worst-case running time for most search-tree operations is proportional to the height of the tree. (a) A binary search tree on 6 nodes with height 2. (b) A less efﬁcient binary search tree with height 4 that contains the same keys. its right child, and its parent, respectively. If a child or the parent is missing, the appropriate attribute contains the value NIL. The root node is the only node in the treewhoseparentisNIL. The keys in a binary search tree are always stored in such a way as to satisfy the binary-search-tree property: Let x be a node in a binary search tree. If y is a node in the left subtree of x,theny:key x:key.Ify is a node in the right subtree of x,then y:key x:key. Thus, in Figure 12.1(a), the key of the root is 6, the keys 2, 5,and5 in its left subtree are no larger than 6,andthekeys7 and 8 in its right subtree are no smaller than 6. The same property holds for every node in the tree. For example, the key 5 in the root’s left child is no smaller than the key 2 in that node’s left subtree and no larger than the key 5 in the right subtree. The binary-search-tree property allows us to print out all the keys in a binary search tree in sorted order by a simple recursive algorithm, called an inorder tree walk. This algorithm is so named because it prints the key of the root of a subtree between printing the values in its left subtree and printing those in its right subtree. (Similarly, a preorder tree walk prints the root before the values in either subtree, and a postorder tree walk prints the root after the values in its subtrees.) To use the following procedure to print all the elements in a binary search tree T , we call INORDER-TREE-WALK.T:root/.288 Chapter 12 Binary Search Trees INORDER-TREE-WALK.x/ 1 if x ¤ NIL 2INORDER-TREE-WALK.x:left/ 3 print x:key 4INORDER-TREE-WALK.x:right/ As an example, the inorder tree walk prints the keys in each of the two binary search trees from Figure 12.1 in the order 2; 5; 5; 6; 7; 8. The correctness of the algorithm follows by induction directly from the binary-search-tree property. It takes ‚.n/ timetowalkann-node binary search tree, since after the ini- tial call, the procedure calls itself recursively exactly twice for each node in the tree—once for its left child and once for its right child. The following theorem gives a formal proof that it takes linear time to perform an inorder tree walk. Theorem 12.1 If x is the root of an n-node subtree, then the call INORDER-TREE-WALK.x/ takes ‚.n/ time. Proof Let T .n/ denote the time taken by INORDER-TREE-WALK when it is called on the root of an n-node subtree. Since INORDER-TREE-WALK visits all n nodes of the subtree, we have T .n/ D .n/. It remains to show that T .n/ D O.n/. Since INORDER-TREE-WALK takes a small, constant amount of time on an empty subtree (for the test x ¤ NIL), we have T.0/D c for some constant c>0. For n>0, suppose that INORDER-TREE-WALK is called on a node x whose left subtree has k nodes and whose right subtree has n k 1 nodes. The time to perform INORDER-TREE-WALK.x/ is bounded by T .n/ T.k/CT.nk1/Cd for some constant d>0that reﬂects an upper bound on the time to execute the body of INORDER-TREE-WALK.x/, exclusive of the time spent in recursive calls. We use the substitution method to show that T .n/ D O.n/ by proving that T .n/ .c Cd/nCc.Forn D 0,wehave.c Cd/0Cc D c D T.0/.Forn>0, we have T .n/ T.k/C T.n k 1/ C d D ..c C d/k C c/ C ..c C d/.n k 1/ C c/ C d D .c C d/nC c .c C d/C c C d D .c C d/nC c; which completes the proof.12.2 Querying a binary search tree 289 Exercises 12.1-1 For the set of f1; 4; 5; 10; 16; 17; 21g of keys, draw binary search trees of heights 2, 3, 4, 5,and6. 12.1-2 What is the difference between the binary-search-tree property and the min-heap property (see page 153)? Can the min-heap property be used to print out the keys of an n-node tree in sorted order in O.n/ time? Show how, or explain why not. 12.1-3 Give a nonrecursive algorithm that performs an inorder tree walk. (Hint: An easy solution uses a stack as an auxiliary data structure. A more complicated, but ele- gant, solution uses no stack but assumes that we can test two pointers for equality.) 12.1-4 Give recursive algorithms that perform preorder and postorder tree walks in ‚.n/ time on a tree of n nodes. 12.1-5 Argue that since sorting n elements takes .n lg n/ time in the worst case in the comparison model, any comparison-based algorithm for constructing a binary search tree from an arbitrary list of n elements takes .n lg n/ time in the worst case. 12.2 Querying a binary search tree We often need to search for a key stored in a binary search tree. Besides the SEARCH operation, binary search trees can support such queries as MINIMUM, MAXIMUM,SUCCESSOR,andPREDECESSOR. In this section, we shall examine these operations and show how to support each one in time O.h/ on any binary search tree of height h. Searching We use the following procedure to search for a node with a given key in a binary search tree. Given a pointer to the root of the tree and a key k,TREE-SEARCH returns a pointer to a node with key k if one exists; otherwise, it returns NIL.290 Chapter 12 Binary Search Trees 2 4 3 13 7 6 17 20 18 15 9 Figure 12.2 Queries on a binary search tree. To search for the key 13 in the tree, we follow the path 15 ! 6 ! 7 ! 13 from the root. The minimum key in the tree is 2, which is found by following left pointers from the root. The maximum key 20 is found by following right pointers from the root. The successor of the node with key 15 is the node with key 17, since it is the minimum key in the right subtree of 15. The node with key 13 has no right subtree, and thus its successor is its lowest ancestor whose left child is also an ancestor. In this case, the node with key 15 is its successor. TREE-SEARCH.x; k/ 1 if x == NIL or k == x:key 2 return x 3 if k0,allbutO.1=nk / of the nŠ input permutations yield an O.nlg n/ running time. Problems 12-1 Binary search trees with equal keys Equal keys pose a problem for the implementation of binary search trees. a. What is the asymptotic performance of TREE-INSERT when used to insert n items with identical keys into an initially empty binary search tree? We propose to improve TREE-INSERT by testing before line 5 to determine whether ´:key D x:key and by testing before line 11 to determine whether ´:key D y:key.304 Chapter 12 Binary Search Trees If equality holds, we implement one of the following strategies. For each strategy, ﬁnd the asymptotic performance of inserting n items with identical keys into an initially empty binary search tree. (The strategies are described for line 5, in which we compare the keys of ´ and x. Substitute y for x to arrive at the strategies for line 11.) b. Keep a boolean ﬂag x:b at node x, and set x to either x:left or x:right based on the value of x:b, which alternates between FALSE and TRUE each time we visit x while inserting a node with the same key as x. c. Keep a list of nodes with equal keys at x, and insert ´ into the list. d. Randomly set x to either x:left or x:right. (Give the worst-case performance and informally derive the expected running time.) 12-2 Radix trees Given two strings a D a0a1 :::ap and b D b0b1 :::bq, where each ai and each bj is in some ordered set of characters, we say that string a is lexicographically less than string b if either 1. there exists an integer j ,where0 j min.p; q/, such that ai D bi for all i D 0; 1; : : : ; j 1 and aj 1, the tree has at least one red node. 13.3-6 Suggest how to implement RB-INSERT efﬁciently if the representation for red- black trees includes no storage for parent pointers.13.4 Deletion 323 13.4 Deletion Like the other basic operations on an n-node red-black tree, deletion of a node takes time O.lg n/. Deleting a node from a red-black tree is a bit more complicated than inserting a node. The procedure for deleting a node from a red-black tree is based on the TREE- DELETE procedure (Section 12.3). First, we need to customize the TRANSPLANT subroutine that TREE-DELETE calls so that it applies to a red-black tree: RB-TRANSPLANT.T;u;/ 1 if u:p == T:nil 2 T:root D 3 elseif u == u:p:left 4 u:p:left D 5 else u:p:right D 6 :p D u:p The procedure RB-TRANSPLANT differs from TRANSPLANT in two ways. First, line 1 references the sentinel T:nil instead of NIL. Second, the assignment to :p in line 6 occurs unconditionally: we can assign to :p even if points to the sentinel. In fact, we shall exploit the ability to assign to :p when D T:nil. The procedure RB-DELETE is like the TREE-DELETE procedure, but with ad- ditional lines of pseudocode. Some of the additional lines keep track of a node y that might cause violations of the red-black properties. When we want to delete node ´ and ´ has fewer than two children, then ´ is removed from the tree, and we want y to be ´.When´ has two children, then y should be ´’s successor, and y moves into ´’s position in the tree. We also remember y’s color before it is re- moved from or moved within the tree, and we keep track of the node x that moves into y’s original position in the tree, because node x might also cause violations of the red-black properties. After deleting node ´, RB-DELETE calls an auxiliary procedure RB-DELETE-FIXUP, which changes colors and performs rotations to restore the red-black properties.324 Chapter 13 Red-Black Trees RB-DELETE.T; ´/ 1 y D ´ 2 y-original-color D y:color 3 if ´:left == T:nil 4 x D ´:right 5 RB-TRANSPLANT.T;´;´:right/ 6 elseif ´:right == T:nil 7 x D ´:left 8 RB-TRANSPLANT.T;´;´:left/ 9 else y D TREE-MINIMUM.´:right/ 10 y-original-color D y:color 11 x D y:right 12 if y:p == ´ 13 x:p D y 14 else RB-TRANSPLANT.T;y;y:right/ 15 y:right D ´:right 16 y:right:p D y 17 RB-TRANSPLANT.T;´;y/ 18 y:left D ´:left 19 y:left:p D y 20 y:color D ´:color 21 if y-original-color == BLACK 22 RB-DELETE-FIXUP.T; x/ Although RB-DELETE contains almost twice as many lines of pseudocode as TREE-DELETE, the two procedures have the same basic structure. You can ﬁnd each line of TREE-DELETE within RB-DELETE (with the changes of replacing NIL by T:nil and replacing calls to TRANSPLANT by calls to RB-TRANSPLANT), executed under the same conditions. Here are the other differences between the two procedures: We maintain node y as the node either removed from the tree or moved within the tree. Line 1 sets y to point to node ´ when ´ has fewer than two children and is therefore removed. When ´ has two children, line 9 sets y to point to ´’s successor, just as in TREE-DELETE,andy will move into ´’s position in the tree. Because node y’s color might change, the variable y-original-color stores y’s color before any changes occur. Lines 2 and 10 set this variable immediately after assignments to y.When´ has two children, then y ¤ ´ and node y moves into node ´’s original position in the red-black tree; line 20 gives y the same color as ´. We need to save y’s original color in order to test it at the13.4 Deletion 325 end of RB-DELETE; if it was black, then removing or moving y could cause violations of the red-black properties. As discussed, we keep track of the node x that moves into node y’s original position. The assignments in lines 4, 7, and 11 set x to point to either y’s only child or, if y has no children, the sentinel T:nil. (Recall from Section 12.3 that y has no left child.) Since node x moves into node y’s original position, the attribute x:p is always set to point to the original position in the tree of y’s parent, even if x is, in fact, the sentinel T:nil. Unless ´ is y’s original parent (which occurs only when ´ has two children and its successor y is ´’s right child), the assignment to x:p takes place in line 6 of RB-TRANSPLANT. (Observe that when RB-TRANSPLANT is called in lines 5, 8, or 14, the second parameter passed is the same as x.) When y’s original parent is ´, however, we do not want x:p to point to y’s orig- inal parent, since we are removing that node from the tree. Because node y will move up to take ´’s position in the tree, setting x:p to y in line 13 causes x:p to point to the original position of y’s parent, even if x D T:nil. Finally, if node y was black, we might have introduced one or more violations of the red-black properties, and so we call RB-DELETE-FIXUP in line 22 to restore the red-black properties. If y was red, the red-black properties still hold when y is removed or moved, for the following reasons: 1. No black-heights in the tree have changed. 2. No red nodes have been made adjacent. Because y takes ´’s place in the tree, along with ´’s color, we cannot have two adjacent red nodes at y’s new position in the tree. In addition, if y was not ´’s right child, then y’s original right child x replaces y in the tree. If y is red, then x must be black, and so replacing y by x cannot cause two red nodes to become adjacent. 3. Since y could not have been the root if it was red, the root remains black. If node y was black, three problems may arise, which the call of RB-DELETE- FIXUP will remedy. First, if y had been the root and a red child of y becomes the new root, we have violated property 2. Second, if both x and x:p are red, then we have violated property 4. Third, moving y within the tree causes any simple path that previously contained y to have one fewer black node. Thus, property 5 is now violated by any ancestor of y in the tree. We can correct the violation of property 5 by saying that node x, now occupying y’s original position, has an “extra” black. That is, if we add 1 to the count of black nodes on any simple path that contains x, then under this interpretation, property 5 holds. When we remove or move the black node y, we “push” its blackness onto node x. The problem is that now node x is neither red nor black, thereby violating property 1. Instead,326 Chapter 13 Red-Black Trees node x is either “doubly black” or “red-and-black,” and it contributes either 2 or 1, respectively, to the count of black nodes on simple paths containing x.Thecolor attribute of x will still be either RED (if x is red-and-black) or BLACK (if x is doubly black). In other words, the extra black on a node is reﬂected in x’s pointing to the node rather than in the color attribute. We can now see the procedure RB-DELETE-FIXUP and examine how it restores the red-black properties to the search tree. RB-DELETE-FIXUP.T; x/ 1 while x ¤ T:root and x:color == BLACK 2 if x == x:p:left 3 w D x:p:right 4 if w:color == RED 5 w:color D BLACK // case 1 6 x:p:color D RED // case 1 7LEFT-ROTATE.T; x:p/ // case 1 8 w D x:p:right // case 1 9 if w:left:color == BLACK and w:right:color == BLACK 10 w:color D RED // case 2 11 x D x:p // case 2 12 else if w:right:color == BLACK 13 w:left:color D BLACK // case 3 14 w:color D RED // case 3 15 RIGHT-ROTATE.T; w/ // case 3 16 w D x:p:right // case 3 17 w:color D x:p:color // case 4 18 x:p:color D BLACK // case 4 19 w:right:color D BLACK // case 4 20 LEFT-ROTATE.T; x:p/ // case 4 21 x D T:root // case 4 22 else (same as then clause with “right” and “left” exchanged) 23 x:color D BLACK The procedure RB-DELETE-FIXUP restores properties 1, 2, and 4. Exercises 13.4-1 and 13.4-2 ask you to show that the procedure restores properties 2 and 4, and so in the remainder of this section, we shall focus on property 1. The goal of the while loop in lines 1–22 is to move the extra black up the tree until 1. x points to a red-and-black node, in which case we color x (singly) black in line 23; 2. x points to the root, in which case we simply “remove” the extra black; or 3. having performed suitable rotations and recolorings, we exit the loop.13.4 Deletion 327 Within the while loop, x always points to a nonroot doubly black node. We determine in line 2 whether x is a left child or a right child of its parent x:p.(We have given the code for the situation in which x is a left child; the situation in which x is a right child—line 22—is symmetric.) We maintain a pointer w to the sibling of x. Since node x is doubly black, node w cannot be T:nil, because otherwise, the number of blacks on the simple path from x:p to the (singly black) leaf w would be smaller than the number on the simple path from x:p to x. The four cases2 in the code appear in Figure 13.7. Before examining each case in detail, let’s look more generally at how we can verify that the transformation in each of the cases preserves property 5. The key idea is that in each case, the transformation applied preserves the number of black nodes (including x’s extra black) from (and including) the root of the subtree shown to each of the subtrees ˛;ˇ;:::;. Thus, if property 5 holds prior to the transformation, it continues to hold afterward. For example, in Figure 13.7(a), which illustrates case 1, the num- ber of black nodes from the root to either subtree ˛ or ˇ is 3, both before and after the transformation. (Again, remember that node x adds an extra black.) Similarly, the number of black nodes from the root to any of , ı, ",and is 2, both be- fore and after the transformation. In Figure 13.7(b), the counting must involve the value c of the color attribute of the root of the subtree shown, which can be either RED or BLACK. If we deﬁne count.RED/ D 0 and count.BLACK/ D 1, then the number of black nodes from the root to ˛ is 2 C count.c/, both before and after the transformation. In this case, after the transformation, the new node x has color attribute c, but this node is really either red-and-black (if c D RED) or doubly black (if c D BLACK). You can verify the other cases similarly (see Exercise 13.4-5). Case 1: x’s sibling w is red Case 1 (lines 5–8 of RB-DELETE-FIXUP and Figure 13.7(a)) occurs when node w, the sibling of node x, is red. Since w must have black children, we can switch the colors of w and x:p and then perform a left-rotation on x:p without violating any of the red-black properties. The new sibling of x, which is one of w’s children prior to the rotation, is now black, and thus we have converted case 1 into case 2, 3, or 4. Cases 2, 3, and 4 occur when node w is black; they are distinguished by the colors of w’s children. 2As in RB-INSERT-FIXUP, the cases in RB-DELETE-FIXUP are not mutually exclusive.328 Chapter 13 Red-Black Trees Case 2: x’s sibling w is black, and both of w’s children are black In case 2 (lines 10–11 of RB-DELETE-FIXUP and Figure 13.7(b)), both of w’s children are black. Since w is also black, we take one black off both x and w, leaving x with only one black and leaving w red. To compensate for removing one black from x and w, we would like to add an extra black to x:p,whichwas originally either red or black. We do so by repeating the while loop with x:p as the new node x. Observe that if we enter case 2 through case 1, the new node x is red-and-black, since the original x:p was red. Hence, the value c of the color attribute of the new node x is RED, and the loop terminates when it tests the loop condition. We then color the new node x (singly) black in line 23. Case 3: x’s sibling w is black, w’s left child is red, and w’s right child is black Case 3 (lines 13–16 and Figure 13.7(c)) occurs when w is black, its left child is red, and its right child is black. We can switch the colors of w and its left child w:left and then perform a right rotation on w without violating any of the red-black properties. The new sibling w of x is now a black node with a red right child, and thus we have transformed case 3 into case 4. Case 4: x’s sibling w is black, and w’s right child is red Case 4 (lines 17–21 and Figure 13.7(d)) occurs when node x’s sibling w is black and w’s right child is red. By making some color changes and performing a left ro- tation on x:p, we can remove the extra black on x, making it singly black, without violating any of the red-black properties. Setting x to be the root causes the while loop to terminate when it tests the loop condition. Analysis What is the running time of RB-DELETE? Since the height of a red-black tree of n nodes is O.lg n/, the total cost of the procedure without the call to RB-DELETE- FIXUP takes O.lg n/ time. Within RB-DELETE-FIXUP, each of cases 1, 3, and 4 lead to termination after performing a constant number of color changes and at most three rotations. Case 2 is the only case in which the while loop can be re- peated, and then the pointer x moves up the tree at most O.lg n/ times, performing no rotations. Thus, the procedure RB-DELETE-FIXUP takes O.lg n/ time and per- forms at most three rotations, and the overall time for RB-DELETE is therefore also O.lg n/.13.4 Deletion 329 A B D CEαβ γδεζ xw A B C D E x new w αβγδ εζ A B D CEαβ γδεζ xw c A B D CEαβ γδεζ cnew x A B D C Eαβ γδεζ xw c A B C Dαβ γ δ εζ x c new w A B D CEαβ γδ εζ xw c c αβ A B C D E(d) (c) (b) (a) γδεζ Case 4 Case 3 Case 2 Case 1 E c′ c′ new x D T:root Figure 13.7 The cases in the while loop of the procedure RB-DELETE-FIXUP. Darkened nodes have color attributes BLACK, heavily shaded nodes have color attributes RED, and lightly shaded nodes have color attributes represented by c and c0, which may be either RED or BLACK. The letters ˛;ˇ;:::; represent arbitrary subtrees. Each case transforms the conﬁguration on the left into the conﬁguration on the right by changing some colors and/or performing a rotation. Any node pointed to by x has an extra black and is either doubly black or red-and-black. Only case 2 causes the loop to repeat. (a) Case 1 is transformed to case 2, 3, or 4 by exchanging the colors of nodes B and D and performing a left rotation. (b) In case 2, the extra black represented by the pointer x moves up the tree by coloring node D red and setting x to point to node B. If we enter case 2 through case 1, the while loop terminates because the new node x is red-and-black, and therefore the value c of its color attribute is RED. (c) Case 3 is transformed to case 4 by exchanging the colors of nodes C and D and performing a right rotation. (d) Case 4 removes the extra black represented by x by changing some colors and performing a left rotation (without violating the red-black properties), and then the loop terminates.330 Chapter 13 Red-Black Trees Exercises 13.4-1 Argue that after executing RB-DELETE-FIXUP, the root of the tree must be black. 13.4-2 Argue that if in RB-DELETE both x and x:p are red, then property 4 is restored by the call to RB-DELETE-FIXUP.T; x/. 13.4-3 In Exercise 13.3-2, you found the red-black tree that results from successively inserting the keys 41; 38; 31; 12; 19; 8 into an initially empty tree. Now show the red-black trees that result from the successive deletion of the keys in the order 8; 12; 19; 31; 38; 41. 13.4-4 In which lines of the code for RB-DELETE-FIXUP might we examine or modify the sentinel T:nil? 13.4-5 In each of the cases of Figure 13.7, give the count of black nodes from the root of the subtree shown to each of the subtrees ˛;ˇ;:::;, and verify that each count remains the same after the transformation. When a node has a color attribute c or c0, use the notation count.c/ or count.c0/ symbolically in your count. 13.4-6 Professors Skelton and Baron are concerned that at the start of case 1 of RB- DELETE-FIXUP, the node x:p might not be black. If the professors are correct, then lines 5–6 are wrong. Show that x:p must be black at the start of case 1, so that the professors have nothing to worry about. 13.4-7 Suppose that a node x is inserted into a red-black tree with RB-INSERT and then is immediately deleted with RB-DELETE. Is the resulting red-black tree the same as the initial red-black tree? Justify your answer.Problems for Chapter 13 331 Problems 13-1 Persistent dynamic sets During the course of an algorithm, we sometimes ﬁnd that we need to maintain past versions of a dynamic set as it is updated. We call such a set persistent.Onewayto implement a persistent set is to copy the entire set whenever it is modiﬁed, but this approach can slow down a program and also consume much space. Sometimes, we can do much better. Consider a persistent set S with the operations INSERT,DELETE,andSEARCH, which we implement using binary search trees as shown in Figure 13.8(a). We maintain a separate root for every version of the set. In order to insert the key 5 into the set, we create a new node with key 5. This node becomes the left child of a new node with key 7, since we cannot modify the existing node with key 7. Similarly, the new node with key 7 becomes the left child of a new node with key 8 whose right child is the existing node with key 10. The new node with key 8 becomes, in turn, the right child of a new root r0 with key 4 whose left child is the existing node with key 3. We thus copy only part of the tree and share some of the nodes with the original tree, as shown in Figure 13.8(b). Assume that each tree node has the attributes key, left,andright but no parent. (See also Exercise 13.3-6.) 4 3 2 8 710 4 3 2 8 710 4 8 7 5 (b)(a) rrr′ Figure 13.8 (a) A binary search tree with keys 2; 3; 4; 7; 8; 10. (b) The persistent binary search tree that results from the insertion of key 5. The most recent version of the set consists of the nodes reachable from the root r0, and the previous version consists of the nodes reachable from r. Heavily shaded nodes are added when key 5 is inserted.332 Chapter 13 Red-Black Trees a. For a general persistent binary search tree, identify the nodes that we need to change to insert a key k or delete a node y. b. Write a procedure PERSISTENT-TREE-INSERT that, given a persistent tree T and a key k to insert, returns a new persistent tree T 0 that is the result of insert- ing k into T . c. If the height of the persistent binary search tree T is h, what are the time and space requirements of your implementation of PERSISTENT-TREE-INSERT? (The space requirement is proportional to the number of new nodes allocated.) d. Suppose that we had included the parent attribute in each node. In this case, PERSISTENT-TREE-INSERT would need to perform additional copying. Prove that PERSISTENT-TREE-INSERT would then require .n/ time and space, where n is the number of nodes in the tree. e. Show how to use red-black trees to guarantee that the worst-case running time and space are O.lg n/ per insertion or deletion. 13-2 Join operation on red-black trees The join operation takes two dynamic sets S1 and S2 andanelementx such that for any x1 2 S1 and x2 2 S2,wehavex1:key x:key x2:key. It returns a set S D S1 [ fxg [ S2. In this problem, we investigate how to implement the join operation on red-black trees. a. Given a red-black tree T , let us store its black-height as the new attribute T:bh. Argue that RB-INSERT and RB-DELETE can maintain the bh attribute with- out requiring extra storage in the nodes of the tree and without increasing the asymptotic running times. Show that while descending through T , we can de- termine the black-height of each node we visit in O.1/ time per node visited. We wish to implement the operation RB-JOIN.T1;x;T2/, which destroys T1 and T2 and returns a red-black tree T D T1 [fxg[T2.Letn be the total number of nodes in T1 and T2. b. Assume that T1:bh T2:bh. Describe an O.lg n/-time algorithm that ﬁnds a black node y in T1 with the largest key from among those nodes whose black- height is T2:bh. c. Let Ty be the subtree rooted at y. Describe how Ty [ fxg [ T2 can replace Ty in O.1/ time without destroying the binary-search-tree property. d. What color should we make x so that red-black properties 1, 3, and 5 are main- tained? Describe how to enforce properties 2 and 4 in O.lg n/ time.Problems for Chapter 13 333 e. Argue that no generality is lost by making the assumption in part (b). Describe the symmetric situation that arises when T1:bh T2:bh. f. Argue that the running time of RB-JOIN is O.lg n/. 13-3 AVL trees An AVL tree is a binary search tree that is height balanced: for each node x,the heights of the left and right subtrees of x differ by at most 1. To implement an AVL tree, we maintain an extra attribute in each node: x:h is the height of node x.As for any other binary search tree T , we assume that T:root points to the root node. a. Prove that an AVL tree with n nodes has height O.lg n/.(Hint: Prove that an AVL tree of height h has at least Fh nodes, where Fh is the hth Fibonacci number.) b. To insert into an AVL tree, we ﬁrst place a node into the appropriate place in bi- nary search tree order. Afterward, the tree might no longer be height balanced. Speciﬁcally, the heights of the left and right children of some node might differ by 2. Describe a procedure BALANCE.x/, which takes a subtree rooted at x whose left and right children are height balanced and have heights that differ by at most 2, i.e., jx:right:h x:left:hj 2, and alters the subtree rooted at x to be height balanced. (Hint: Use rotations.) c. Using part (b), describe a recursive procedure AVL-INSERT.x; ´/ that takes a node x within an AVL tree and a newly created node ´ (whose key has al- ready been ﬁlled in), and adds ´ to the subtree rooted at x, maintaining the property that x is the root of an AVL tree. As in TREE-INSERT from Sec- tion 12.3, assume that ´:key has already been ﬁlled in and that ´:left D NIL and ´:right D NIL; also assume that ´:h D 0. Thus, to insert the node ´ into the AVL tree T , we call AVL-INSERT.T:root;´/. d. Show that AVL-INSERT, run on an n-node AVL tree, takes O.lg n/ time and performs O.1/ rotations. 13-4 Treaps If we insert a set of n items into a binary search tree, the resulting tree may be horribly unbalanced, leading to long search times. As we saw in Section 12.4, however, randomly built binary search trees tend to be balanced. Therefore, one strategy that, on average, builds a balanced tree for a ﬁxed set of items would be to randomly permute the items and then insert them in that order into the tree. What if we do not have all the items at once? If we receive the items one at a time, can we still randomly build a binary search tree out of them?334 Chapter 13 Red-Black Trees G: 4 B: 7 H: 5 A: 10 E: 23 K: 65 I: 73 Figure 13.9 A treap. Each node x is labeled with x:key: x:priority. For example, the root has key G and priority 4. We will examine a data structure that answers this question in the afﬁrmative. A treap is a binary search tree with a modiﬁed way of ordering the nodes. Figure 13.9 shows an example. As usual, each node x in the tree has a key value x:key.In addition, we assign x:priority, which is a random number chosen independently for each node. We assume that all priorities are distinct and also that all keys are distinct. The nodes of the treap are ordered so that the keys obey the binary-search- tree property and the priorities obey the min-heap order property: If is a left child of u,then:key u:key. If is a child of u,then:priority >u:priority. (This combination of properties is why the tree is called a “treap”: it has features of both a binary search tree and a heap.) It helps to think of treaps in the following way. Suppose that we insert nodes x1;x2;:::;xn, with associated keys, into a treap. Then the resulting treap is the tree that would have been formed if the nodes had been inserted into a normal binary search tree in the order given by their (randomly chosen) priorities, i.e., xi :priority x:priority, y:key r,then the ith smallest element resides in x’s right subtree. Since the subtree rooted at x contains r elements that come before x’s right subtree in an inorder tree walk, the ith smallest element in the subtree rooted at x is the .i r/th smallest element in the subtree rooted at x:right. Line 6 determines this element recursively. To see how OS-SELECT operates, consider a search for the 17th smallest ele- ment in the order-statistic tree of Figure 14.1. We begin with x as the root, whose key is 26, and with i D 17. Since the size of 26’s left subtree is 12, its rank is 13. Thus, we know that the node with rank 17 is the 17 13 D 4th smallest element in 26’s right subtree. After the recursive call, x is the node with key 41, and i D 4. Since the size of 41’s left subtree is 5, its rank within its subtree is 6. Thus, we know that the node with rank 4 is the 4th smallest element in 41’s left subtree. Af- ter the recursive call, x is the node with key 30, and its rank within its subtree is 2. Thus, we recurse once again to ﬁnd the 42 D 2nd smallest element in the subtree rooted at the node with key 38. We now ﬁnd that its left subtree has size 1, which means it is the second smallest element. Thus, the procedure returns a pointer to the node with key 38. Because each recursive call goes down one level in the order-statistic tree, the total time for OS-SELECT is at worst proportional to the height of the tree. Since the tree is a red-black tree, its height is O.lg n/,wheren is the number of nodes. Thus, the running time of OS-SELECT is O.lg n/ for a dynamic set of n elements. Determining the rank of an element Given a pointer to a node x in an order-statistic tree T , the procedure OS-RANK returns the position of x in the linear order determined by an inorder tree walk of T .342 Chapter 14 Augmenting Data Structures OS-RANK.T; x/ 1 r D x:left:size C 1 2 y D x 3 while y ¤ T:root 4 if y == y:p:right 5 r D r C y:p:left:size C 1 6 y D y:p 7 return r The procedure works as follows. We can think of node x’s rank as the number of nodes preceding x in an inorder tree walk, plus 1 for x itself. OS-RANK maintains the following loop invariant: At the start of each iteration of the while loop of lines 3–6, r is the rank of x:key in the subtree rooted at node y. We use this loop invariant to show that OS-RANK works correctly as follows: Initialization: Prior to the ﬁrst iteration, line 1 sets r to be the rank of x:key within the subtree rooted at x. Setting y D x in line 2 makes the invariant true the ﬁrst time the test in line 3 executes. Maintenance: At the end of each iteration of the while loop, we set y D y:p. Thus we must show that if r is the rank of x:key in the subtree rooted at y at the start of the loop body, then r is the rank of x:key in the subtree rooted at y:p at the end of the loop body. In each iteration of the while loop, we consider the subtree rooted at y:p. We have already counted the number of nodes in the subtree rooted at node y that precede x in an inorder walk, and so we must add the nodes in the subtree rooted at y’s sibling that precede x in an inorder walk, plus 1 for y:p if it, too, precedes x.Ify is a left child, then neither y:p nor any node in y:p’s right subtree precedes x,andsoweleaver alone. Otherwise, y is a right child and all the nodes in y:p’s left subtree precede x, as does y:p itself. Thus, in line 5, we add y:p:left:size C 1 to the current value of r. Termination: The loop terminates when y D T:root, so that the subtree rooted at y is the entire tree. Thus, the value of r is the rank of x:key in the entire tree. As an example, when we run OS-RANK on the order-statistic tree of Figure 14.1 to ﬁnd the rank of the node with key 38, we get the following sequence of values of y:key and r at the top of the while loop: iteration y:key r 1382 2304 3414 4261714.1 Dynamic order statistics 343 The procedure returns the rank 17. Since each iteration of the while loop takes O.1/ time, and y goes up one level in the tree with each iteration, the running time of OS-RANK is at worst proportional to the height of the tree: O.lg n/ on an n-node order-statistic tree. Maintaining subtree sizes Given the size attribute in each node, OS-SELECT and OS-RANK can quickly compute order-statistic information. But unless we can efﬁciently maintain these attributes within the basic modifying operations on red-black trees, our work will have been for naught. We shall now show how to maintain subtree sizes for both insertion and deletion without affecting the asymptotic running time of either op- eration. We noted in Section 13.3 that insertion into a red-black tree consists of two phases. The ﬁrst phase goes down the tree from the root, inserting the new node as a child of an existing node. The second phase goes up the tree, changing colors and performing rotations to maintain the red-black properties. To maintain the subtree sizes in the ﬁrst phase, we simply increment x:size for each node x on the simple path traversed from the root down toward the leaves. The new node added gets a size of 1. Since there are O.lg n/ nodes on the traversed path, the additional cost of maintaining the size attributes is O.lg n/. In the second phase, the only structural changes to the underlying red-black tree are caused by rotations, of which there are at most two. Moreover, a rotation is a local operation: only two nodes have their size attributes invalidated. The link around which the rotation is performed is incident on these two nodes. Referring to the code for LEFT-ROTATE.T; x/ in Section 13.2, we add the following lines: 13 y:size D x:size 14 x:size D x:left:size C x:right:size C 1 Figure 14.2 illustrates how the attributes are updated. The change to RIGHT- ROTATE is symmetric. Since at most two rotations are performed during insertion into a red-black tree, we spend only O.1/ additional time updating size attributes in the second phase. Thus, the total time for insertion into an n-node order-statistic tree is O.lg n/, which is asymptotically the same as for an ordinary red-black tree. Deletion from a red-black tree also consists of two phases: the ﬁrst operates on the underlying search tree, and the second causes at most three rotations and otherwise performs no structural changes. (See Section 13.4.) The ﬁrst phase either removes one node y from the tree or moves upward it within the tree. To update the subtree sizes, we simply traverse a simple path from node y (starting from its original position within the tree) up to the root, decrementing the size344 Chapter 14 Augmenting Data Structures LEFT-ROTATE(T, x) RIGHT-ROTATE(T, y) 93 19 y 42 11 x 6 4 7 93 42 19 12 6 4 7 x y Figure 14.2 Updating subtree sizes during rotations. The link around which we rotate is incident on the two nodes whose size attributes need to be updated. The updates are local, requiring only the size information stored in x, y, and the roots of the subtrees shown as triangles. attribute of each node on the path. Since this path has length O.lg n/ in an n- node red-black tree, the additional time spent maintaining size attributes in the ﬁrst phase is O.lg n/. We handle the O.1/ rotations in the second phase of deletion in the same manner as for insertion. Thus, both insertion and deletion, including maintaining the size attributes, take O.lg n/ time for an n-node order-statistic tree. Exercises 14.1-1 Show how OS-SELECT.T:root; 10/ operates on the red-black tree T of Fig- ure 14.1. 14.1-2 Show how OS-RANK.T; x/ operates on the red-black tree T of Figure 14.1 and the node x with x:key D 35. 14.1-3 Write a nonrecursive version of OS-SELECT. 14.1-4 Write a recursive procedure OS-KEY-RANK.T; k/ that takes as input an order- statistic tree T and a key k and returns the rank of k in the dynamic set represented by T . Assume that the keys of T are distinct. 14.1-5 Given an element x in an n-node order-statistic tree and a natural number i,how can we determine the ith successor of x in the linear order of the tree in O.lg n/ time?14.2 How to augment a data structure 345 14.1-6 Observe that whenever we reference the size attribute of a node in either OS- SELECT or OS-RANK, we use it only to compute a rank. Accordingly, suppose we store in each node its rank in the subtree of which it is the root. Show how to maintain this information during insertion and deletion. (Remember that these two operations can cause rotations.) 14.1-7 Show how to use an order-statistic tree to count the number of inversions (see Problem 2-4) in an array of size n in time O.nlg n/. 14.1-8 ? Consider n chords on a circle, each deﬁned by its endpoints. Describe an O.nlg n/- time algorithm to determine the number of pairs of chords that intersect inside the circle. (For example, if the n chords are all diameters that meet at the center, then the correct answer is n 2 .) Assume that no two chords share an endpoint. 14.2 How to augment a data structure The process of augmenting a basic data structure to support additional functionality occurs quite frequently in algorithm design. We shall use it again in the next section to design a data structure that supports operations on intervals. In this section, we examine the steps involved in such augmentation. We shall also prove a theorem that allows us to augment red-black trees easily in many cases. We can break the process of augmenting a data structure into four steps: 1. Choose an underlying data structure. 2. Determine additional information to maintain in the underlying data structure. 3. Verify that we can maintain the additional information for the basic modifying operations on the underlying data structure. 4. Develop new operations. As with any prescriptive design method, you should not blindly follow the steps in the order given. Most design work contains an element of trial and error, and progress on all steps usually proceeds in parallel. There is no point, for example, in determining additional information and developing new operations (steps 2 and 4) if we will not be able to maintain the additional information efﬁciently. Neverthe- less, this four-step method provides a good focus for your efforts in augmenting a data structure, and it is also a good way to organize the documentation of an augmented data structure.346 Chapter 14 Augmenting Data Structures We followed these steps in Section 14.1 to design our order-statistic trees. For step 1, we chose red-black trees as the underlying data structure. A clue to the suitability of red-black trees comes from their efﬁcient support of other dynamic- set operations on a total order, such as MINIMUM,MAXIMUM,SUCCESSOR,and PREDECESSOR. For step 2, we added the size attribute, in which each node x stores the size of the subtree rooted at x. Generally, the additional information makes operations more efﬁcient. For example, we could have implemented OS-SELECT and OS-RANK using just the keys stored in the tree, but they would not have run in O.lg n/ time. Sometimes, the additional information is pointer information rather than data, as in Exercise 14.2-1. For step 3, we ensured that insertion and deletion could maintain the size at- tributes while still running in O.lg n/ time. Ideally, we should need to update only a few elements of the data structure in order to maintain the additional information. For example, if we simply stored in each node its rank in the tree, the OS-SELECT and OS-RANK procedures would run quickly, but inserting a new minimum ele- ment would cause a change to this information in every node of the tree. When we store subtree sizes instead, inserting a new element causes information to change in only O.lg n/ nodes. For step 4, we developed the operations OS-SELECT and OS-RANK. After all, the need for new operations is why we bother to augment a data structure in the ﬁrst place. Occasionally, rather than developing new operations, we use the additional information to expedite existing ones, as in Exercise 14.2-1. Augmenting red-black trees When red-black trees underlie an augmented data structure, we can prove that in- sertion and deletion can always efﬁciently maintain certain kinds of additional in- formation, thereby making step 3 very easy. The proof of the following theorem is similar to the argument from Section 14.1 that we can maintain the size attribute for order-statistic trees. Theorem 14.1 (Augmenting a red-black tree) Let f be an attribute that augments a red-black tree T of n nodes, and suppose that the value of f for each node x depends on only the information in nodes x, x:left, and x:right, possibly including x:left:f and x:right:f. Then, we can maintain the values of f in all nodes of T during insertion and deletion without asymptotically affecting the O.lg n/ performance of these operations. Proof The main idea of the proof is that a change to an f attribute in a node x propagates only to ancestors of x in the tree. That is, changing x:f may re-14.2 How to augment a data structure 347 quire x:p:f to be updated, but nothing else; updating x:p:f may require x:p:p:f to be updated, but nothing else; and so on up the tree. Once we have updated T:root:f, no other node will depend on the new value, and so the process termi- nates. Since the height of a red-black tree is O.lg n/, changing an f attribute in a node costs O.lg n/ time in updating all nodes that depend on the change. Insertion of a node x into T consists of two phases. (See Section 13.3.) The ﬁrst phase inserts x as a child of an existing node x:p. We can compute the value of x:f in O.1/ time since, by supposition, it depends only on information in the other attributes of x itself and the information in x’s children, but x’s children are both the sentinel T:nil. Once we have computed x:f, the change propagates up the tree. Thus, the total time for the ﬁrst phase of insertion is O.lg n/. During the second phase, the only structural changes to the tree come from rotations. Since only two nodes change in a rotation, the total time for updating the f attributes is O.lg n/ per rotation. Since the number of rotations during insertion is at most two, the total time for insertion is O.lg n/. Like insertion, deletion has two phases. (See Section 13.4.) In the ﬁrst phase, changes to the tree occur when the deleted node is removed from the tree. If the deleted node had two children at the time, then its successor moves into the position of the deleted node. Propagating the updates to f caused by these changes costs at most O.lg n/, since the changes modify the tree locally. Fixing up the red-black tree during the second phase requires at most three rotations, and each rotation requires at most O.lg n/ time to propagate the updates to f . Thus, like insertion, the total time for deletion is O.lg n/. In many cases, such as maintaining the size attributes in order-statistic trees, the cost of updating after a rotation is O.1/, rather than the O.lg n/ derived in the proof of Theorem 14.1. Exercise 14.2-3 gives an example. Exercises 14.2-1 Show, by adding pointers to the nodes, how to support each of the dynamic-set queries MINIMUM,MAXIMUM,SUCCESSOR,andPREDECESSOR in O.1/ worst- case time on an augmented order-statistic tree. The asymptotic performance of other operations on order-statistic trees should not be affected. 14.2-2 Can we maintain the black-heights of nodes in a red-black tree as attributes in the nodes of the tree without affecting the asymptotic performance of any of the red- black tree operations? Show how, or argue why not. How about maintaining the depths of nodes?348 Chapter 14 Augmenting Data Structures 14.2-3 ? Let ˝ be an associative binary operator, and let a be an attribute maintained in each node of a red-black tree. Suppose that we want to include in each node x an addi- tional attribute f such that x:f D x1:a ˝ x2:a ˝˝xm:a,wherex1;x2;:::;xm is the inorder listing of nodes in the subtree rooted at x. Show how to update the f attributes in O.1/ time after a rotation. Modify your argument slightly to apply it to the size attributes in order-statistic trees. 14.2-4 ? We wish to augment red-black trees with an operation RB-ENUMERATE.x;a;b/ that outputs all the keys k such that a k b in a red-black tree rooted at x. Describe how to implement RB-ENUMERATE in ‚.mClg n/ time, where m is the number of keys that are output and n is the number of internal nodes in the tree. (Hint: You do not need to add new attributes to the red-black tree.) 14.3 Interval trees In this section, we shall augment red-black trees to support operations on dynamic sets of intervals. A closed interval is an ordered pair of real numbers Œt1;t2, with t1 t2. The interval Œt1;t2 represents the set ft 2 R W t1 t t2g. Open and half-open intervals omit both or one of the endpoints from the set, respectively. In this section, we shall assume that intervals are closed; extending the results to open and half-open intervals is conceptually straightforward. Intervals are convenient for representing events that each occupy a continuous period of time. We might, for example, wish to query a database of time intervals to ﬁnd out what events occurred during a given interval. The data structure in this section provides an efﬁcient means for maintaining such an interval database. We can represent an interval Œt1;t2 as an object i, with attributes i:low D t1 (the low endpoint)andi:high D t2 (the high endpoint). We say that intervals i and i 0 overlap if i \ i 0 ¤;,thatis,ifi:low i 0:high and i 0:low i:high.As Figure 14.3 shows, any two intervals i and i 0 satisfy the interval trichotomy;that is, exactly one of the following three properties holds: a. i and i 0 overlap, b. i is to the left of i 0 (i.e., i:high 0 3 print sŒn 4 n D n sŒn In our rod-cutting example, the call EXTENDED-BOTTOM-UP-CUT-ROD.p; 10/ would return the following arrays: i 012345678910 rŒi 0 1 5 8 10 13 17 18 22 25 30 sŒi 012322612310 A call to PRINT-CUT-ROD-SOLUTION.p; 10/ would print just 10, but a call with n D 7 would print the cuts 1 and 6, corresponding to the ﬁrst optimal decomposi- tion for r7 given earlier. Exercises 15.1-1 Show that equation (15.4) follows from equation (15.3) and the initial condition T.0/D 1.370 Chapter 15 Dynamic Programming 15.1-2 Show, by means of a counterexample, that the following “greedy” strategy does not always determine an optimal way to cut rods. Deﬁne the density of a rod of length i to be pi =i, that is, its value per inch. The greedy strategy for a rod of length n cuts off a ﬁrst piece of length i,where1 i n, having maximum density. It then continues by applying the greedy strategy to the remaining piece of length n i. 15.1-3 Consider a modiﬁcation of the rod-cutting problem in which, in addition to a price pi for each rod, each cut incurs a ﬁxed cost of c. The revenue associated with a solution is now the sum of the prices of the pieces minus the costs of making the cuts. Give a dynamic-programming algorithm to solve this modiﬁed problem. 15.1-4 Modify MEMOIZED-CUT-ROD to return not only the value but the actual solution, too. 15.1-5 The Fibonacci numbers are deﬁned by recurrence (3.22). Give an O.n/-time dynamic-programming algorithm to compute the nth Fibonacci number. Draw the subproblem graph. How many vertices and edges are in the graph? 15.2 Matrix-chain multiplication Our next example of dynamic programming is an algorithm that solves the problem of matrix-chain multiplication. We are given a sequence (chain) hA1;A2;:::;Ani of n matrices to be multiplied, and we wish to compute the product A1A2 An : (15.5) We can evaluate the expression (15.5) using the standard algorithm for multiply- ing pairs of matrices as a subroutine once we have parenthesized it to resolve all ambiguities in how the matrices are multiplied together. Matrix multiplication is associative, and so all parenthesizations yield the same product. A product of ma- trices is fully parenthesized if it is either a single matrix or the product of two fully parenthesized matrix products, surrounded by parentheses. For example, if the chain of matrices is hA1;A2;A3;A4i, then we can fully parenthesize the product A1A2A3A4 in ﬁve distinct ways:15.2 Matrix-chain multiplication 371 .A1.A2.A3A4/// ; .A1..A2A3/A4// ; ..A1A2/.A3A4// ; ..A1.A2A3//A4/; ...A1A2/A3/A4/: How we parenthesize a chain of matrices can have a dramatic impact on the cost of evaluating the product. Consider ﬁrst the cost of multiplying two matrices. The standard algorithm is given by the following pseudocode, which generalizes the SQUARE-MATRIX-MULTIPLY procedure from Section 4.2. The attributes rows and columns are the numbers of rows and columns in a matrix. MATRIX-MULTIPLY.A; B/ 1 if A:columns ¤ B:rows 2 error “incompatible dimensions” 3 else let C beanewA:rows B:columns matrix 4 for i D 1 to A:rows 5 for j D 1 to B:columns 6 cij D 0 7 for k D 1 to A:columns 8 cij D cij C aik bkj 9 return C We can multiply two matrices A and B only if they are compatible: the number of columns of A must equal the number of rows of B.IfA is a p q matrix and B is a q r matrix, the resulting matrix C is a p r matrix. The time to compute C is dominated by the number of scalar multiplications in line 8, which is pqr.Inwhat follows, we shall express costs in terms of the number of scalar multiplications. To illustrate the different costs incurred by different parenthesizations of a matrix product, consider the problem of a chain hA1;A2;A3i of three matrices. Suppose that the dimensions of the matrices are 10 100, 100 5,and5 50, respec- tively. If we multiply according to the parenthesization ..A1A2/A3/, we perform 10 100 5 D 5000 scalar multiplications to compute the 10 5 matrix prod- uct A1A2, plus another 10 5 50 D 2500 scalar multiplications to multiply this matrix by A3, for a total of 7500 scalar multiplications. If instead we multiply according to the parenthesization .A1.A2A3//, we perform 100 5 50 D 25,000 scalar multiplications to compute the 100 50 matrix product A2A3, plus another 10 100 50 D 50,000 scalar multiplications to multiply A1 by this matrix, for a total of 75,000 scalar multiplications. Thus, computing the product according to the ﬁrst parenthesization is 10 times faster. We state the matrix-chain multiplication problem as follows: given a chain hA1;A2;:::;Ani of n matrices, where for i D 1;2;:::;n, matrix Ai has dimension372 Chapter 15 Dynamic Programming pi1 pi , fully parenthesize the product A1A2 An in a way that minimizes the number of scalar multiplications. Note that in the matrix-chain multiplication problem, we are not actually multi- plying matrices. Our goal is only to determine an order for multiplying matrices that has the lowest cost. Typically, the time invested in determining this optimal order is more than paid for by the time saved later on when actually performing the matrix multiplications (such as performing only 7500 scalar multiplications instead of 75,000). Counting the number of parenthesizations Before solving the matrix-chain multiplication problem by dynamic programming, let us convince ourselves that exhaustively checking all possible parenthesizations does not yield an efﬁcient algorithm. Denote the number of alternative parenthe- sizations of a sequence of n matrices by P.n/.Whenn D 1, we have just one matrix and therefore only one way to fully parenthesize the matrix product. When n 2, a fully parenthesized matrix product is the product of two fully parenthe- sized matrix subproducts, and the split between the two subproducts may occur between the kth and .k C 1/st matrices for any k D 1;2;:::;n 1. Thus, we obtain the recurrence P.n/ D 1 if n D 1; n1X kD1 P.k/P.n k/ if n 2: (15.6) Problem 12-4 asked you to show that the solution to a similar recurrence is the sequence of Catalan numbers, which grows as .4n=n3=2/. A simpler exercise (see Exercise 15.2-3) is to show that the solution to the recurrence (15.6) is .2n/. The number of solutions is thus exponential in n, and the brute-force method of exhaustive search makes for a poor strategy when determining how to optimally parenthesize a matrix chain. Applying dynamic programming We shall use the dynamic-programming method to determine how to optimally parenthesize a matrix chain. In so doing, we shall follow the four-step sequence that we stated at the beginning of this chapter: 1. Characterize the structure of an optimal solution. 2. Recursively deﬁne the value of an optimal solution. 3. Compute the value of an optimal solution.15.2 Matrix-chain multiplication 373 4. Construct an optimal solution from computed information. We shall go through these steps in order, demonstrating clearly how we apply each step to the problem. Step 1: The structure of an optimal parenthesization For our ﬁrst step in the dynamic-programming paradigm, we ﬁnd the optimal sub- structure and then use it to construct an optimal solution to the problem from opti- mal solutions to subproblems. In the matrix-chain multiplication problem, we can perform this step as follows. For convenience, let us adopt the notation Ai::j,where i j , for the matrix that results from evaluating the product Ai AiC1 Aj .Ob- serve that if the problem is nontrivial, i.e., i1: Noting that for i D 1;2;:::;n 1, each term T.i/appears once as T.k/and once as T.n k/, and collecting the n 11s in the summation together with the 1 out front, we can rewrite the recurrence as T .n/ 2 n1X iD1 T.i/C n: (15.8) We shall prove that T .n/ D .2n/ using the substitution method. Speciﬁ- cally, we shall show that T .n/ 2n1 for all n 1. The basis is easy, since T.1/ 1 D 20. Inductively, for n 2 we have T .n/ 2 n1X iD1 2i1 C n D 2 n2X iD0 2i C n D 2.2n1 1/ C n (by equation (A.5)) D 2n 2 C n 2n1 ; which completes the proof. Thus, the total amount of work performed by the call RECURSIVE-MATRIX-CHAIN.p;1;n/is at least exponential in n. Compare this top-down, recursive algorithm (without memoization) with the bottom-up dynamic-programming algorithm. The latter is more efﬁcient because it takes advantage of the overlapping-subproblems property. Matrix-chain mul- tiplication has only ‚.n2/ distinct subproblems, and the dynamic-programming algorithm solves each exactly once. The recursive algorithm, on the other hand, must again solve each subproblem every time it reappears in the recursion tree. Whenever a recursion tree for the natural recursive solution to a problem contains the same subproblem repeatedly, and the total number of distinct subproblems is small, dynamic programming can improve efﬁciency, sometimes dramatically.15.3 Elements of dynamic programming 387 Reconstructing an optimal solution As a practical matter, we often store which choice we made in each subproblem in a table so that we do not have to reconstruct this information from the costs that we stored. For matrix-chain multiplication, the table sŒi;j saves us a signiﬁcant amount of work when reconstructing an optimal solution. Suppose that we did not maintain the sŒi;j table, having ﬁlled in only the table mŒi; j containing optimal subprob- lem costs. We choose from among j i possibilities when we determine which subproblems to use in an optimal solution to parenthesizing Ai AiC1 Aj ,and j i is not a constant. Therefore, it would take ‚.j i/ D !.1/ time to recon- struct which subproblems we chose for a solution to a given problem. By storing in sŒi;j the index of the matrix at which we split the product Ai AiC1 Aj ,we can reconstruct each choice in O.1/ time. Memoization As we saw for the rod-cutting problem, there is an alternative approach to dy- namic programming that often offers the efﬁciency of the bottom-up dynamic- programming approach while maintaining a top-down strategy. The idea is to memoize the natural, but inefﬁcient, recursive algorithm. As in the bottom-up ap- proach, we maintain a table with subproblem solutions, but the control structure for ﬁlling in the table is more like the recursive algorithm. A memoized recursive algorithm maintains an entry in a table for the solution to each subproblem. Each table entry initially contains a special value to indicate that the entry has yet to be ﬁlled in. When the subproblem is ﬁrst encountered as the recursive algorithm unfolds, its solution is computed and then stored in the table. Each subsequent time that we encounter this subproblem, we simply look up the value stored in the table and return it.5 Here is a memoized version of RECURSIVE-MATRIX-CHAIN. Note where it resembles the memoized top-down method for the rod-cutting problem. 5This approach presupposes that we know the set of all possible subproblem parameters and that we have established the relationship between table positions and subproblems. Another, more general, approach is to memoize by using hashing with the subproblem parameters as keys.388 Chapter 15 Dynamic Programming MEMOIZED-MATRIX-CHAIN.p/ 1 n D p:length 1 2letmŒ1::n;1::nbe a new table 3 for i D 1 to n 4 for j D i to n 5 mŒi; j D1 6 return LOOKUP-CHAIN.m;p;1;n/ LOOKUP-CHAIN.m;p;i;j/ 1 if mŒi; j < 1 2 return mŒi; j 3 if i == j 4 mŒi; j D 0 5 else for k D i to j 1 6 q D LOOKUP-CHAIN.m;p;i;k/ C LOOKUP-CHAIN.m;p;kC 1; j / C pi1pkpj 7 if q 0 and xi D yj ; max.cŒi; j 1; cŒi 1; j / if i;j > 0 and xi ¤ yj : (15.9) Observe that in this recursive formulation, a condition in the problem restricts which subproblems we may consider. When xi D yj , we can and should consider the subproblem of ﬁnding an LCS of Xi1 and Yj1. Otherwise, we instead con- sider the two subproblems of ﬁnding an LCS of Xi and Yj1 and of Xi1 and Yj .In the previous dynamic-programming algorithms we have examined—for rod cutting and matrix-chain multiplication—we ruled out no subproblems due to conditions in the problem. Finding an LCS is not the only dynamic-programming algorithm that rules out subproblems based on conditions in the problem. For example, the edit-distance problem (see Problem 15-5) has this characteristic. Step 3: Computing the length of an LCS Based on equation (15.9), we could easily write an exponential-time recursive al- gorithm to compute the length of an LCS of two sequences. Since the LCS problem394 Chapter 15 Dynamic Programming has only ‚.mn/ distinct subproblems, however, we can use dynamic programming to compute the solutions bottom up. Procedure LCS-LENGTH takes two sequences X Dhx1;x2; :::; xmi and Y Dhy1;y2;:::;yni as inputs. It stores the cŒi;jvalues in a table cŒ0::m;0::n, and it computes the entries in row-major order. (That is, the procedure ﬁlls in the ﬁrst row of c from left to right, then the second row, and so on.) The procedure also maintains the table bŒ1::m;1::nto help us construct an optimal solution. Intu- itively, bŒi;j points to the table entry corresponding to the optimal subproblem solution chosen when computing cŒi;j. The procedure returns the b and c tables; cŒm;n contains the length of an LCS of X and Y . LCS-LENGTH.X; Y / 1 m D X:length 2 n D Y:length 3letbŒ1::m;1::nand cŒ0::m;0::nbe new tables 4 for i D 1 to m 5 cŒi;0 D 0 6 for j D 0 to n 7 cŒ0;j D 0 8 for i D 1 to m 9 for j D 1 to n 10 if xi == yj 11 cŒi;j D cŒi 1; j 1 C 1 12 bŒi;j D “-” 13 elseif cŒi 1; j cŒi;j 1 14 cŒi;j D cŒi 1; j 15 bŒi;j D “"” 16 else cŒi;j D cŒi;j 1 17 bŒi;j D “ ” 18 return c and b Figure 15.8 shows the tables produced by LCS-LENGTH on the sequences X D hA; B; C; B; D; A; Bi and Y DhB; D; C; A; B; Ai. The running time of the procedure is ‚.mn/, since each table entry takes ‚.1/ time to compute. Step 4: Constructing an LCS The b table returned by LCS-LENGTH enables us to quickly construct an LCS of X Dhx1;x2;:::;xmi and Y Dhy1;y2;:::;yni. We simply begin at bŒm;n and trace through the table by following the arrows. Whenever we encounter a “-”in entry bŒi;j, it implies that xi D yj is an element of the LCS that LCS-LENGTH15.4 Longest common subsequence 395 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 2 2 0 1 1 2 2 2 0 1 1 2 2 3 0 1 2 2 2 3 3 0 1 2 2 3 3 0 1 2 2 3 4 4 1 2 3 4 BDCABA 1234560 A B C B D A B 1 2 3 4 5 6 7 0 j i xi yj Figure 15.8 The c and b tables computed by LCS-LENGTH on the sequences X DhA; B; C; B; D; A; Bi and Y DhB;D;C;A;B;Ai. The square in row i and column j contains the value of cŒi; j and the appropriate arrow for the value of bŒi;j.Theentry4 in cŒ7;6—the lower right-hand corner of the table—is the length of an LCS hB; C; B; Ai of X and Y .Fori; j > 0,entrycŒi;j depends only on whether xi D yj and the values in entries cŒi 1; j , cŒi;j 1,andcŒi 1; j 1,which are computed before cŒi;j. To reconstruct the elements of an LCS, follow the bŒi;j arrows from the lower right-hand corner; the sequence is shaded. Each “-” on the shaded sequence corresponds to an entry (highlighted) for which xi D yj isamemberofanLCS. found. With this method, we encounter the elements of this LCS in reverse order. The following recursive procedure prints out an LCS of X and Y in the proper, forward order. The initial call is PRINT-LCS.b;X;X:length;Y:length/. PRINT-LCS.b;X;i;j/ 1 if i == 0 or j == 0 2 return 3 if bŒi;j == “-” 4PRINT-LCS.b;X;i 1; j 1/ 5 print xi 6 elseif bŒi;j == “"” 7PRINT-LCS.b;X;i 1; j / 8 else PRINT-LCS.b;X;i;j 1/ For the b table in Figure 15.8, this procedure prints BCBA. The procedure takes time O.m C n/, since it decrements at least one of i and j in each recursive call.396 Chapter 15 Dynamic Programming Improving the code Once you have developed an algorithm, you will often ﬁnd that you can improve on the time or space it uses. Some changes can simplify the code and improve constant factors but otherwise yield no asymptotic improvement in performance. Others can yield substantial asymptotic savings in time and space. In the LCS algorithm, for example, we can eliminate the b table altogether. Each cŒi;j entry depends on only three other c table entries: cŒi 1; j 1, cŒi 1; j , and cŒi;j 1. Given the value of cŒi;j, we can determine in O.1/ time which of these three values was used to compute cŒi;j, without inspecting table b. Thus, we can reconstruct an LCS in O.mCn/ time using a procedure similar to PRINT-LCS. (Exercise 15.4-2 asks you to give the pseudocode.) Although we save ‚.mn/ space by this method, the auxiliary space requirement for computing an LCS does not asymptotically decrease, since we need ‚.mn/ space for the c table anyway. We can, however, reduce the asymptotic space requirements for LCS-LENGTH, since it needs only two rows of table c at a time: the row being computed and the previous row. (In fact, as Exercise 15.4-4 asks you to show, we can use only slightly more than the space for one row of c to compute the length of an LCS.) This improvement works if we need only the length of an LCS; if we need to reconstruct the elements of an LCS, the smaller table does not keep enough information to retrace our steps in O.m C n/ time. Exercises 15.4-1 Determine an LCS of h1; 0; 0; 1; 0; 1; 0; 1i and h0; 1; 0; 1; 1; 0; 1; 1; 0i. 15.4-2 Give pseudocode to reconstruct an LCS from the completed c table and the original sequences X Dhx1;x2;:::;xmi and Y Dhy1;y2;:::;yni in O.m C n/ time, without using the b table. 15.4-3 Give a memoized version of LCS-LENGTH that runs in O.mn/ time. 15.4-4 Show how to compute the length of an LCS using only 2min.m; n/ entries in the c table plus O.1/ additional space. Then show how to do the same thing, but using min.m; n/ entries plus O.1/ additional space.15.5 Optimal binary search trees 397 15.4-5 Give an O.n2/-time algorithm to ﬁnd the longest monotonically increasing subse- quence of a sequence of n numbers. 15.4-6 ? Give an O.nlg n/-time algorithm to ﬁnd the longest monotonically increasing sub- sequence of a sequence of n numbers. (Hint: Observe that the last element of a candidate subsequence of length i is at least as large as the last element of a can- didate subsequence of length i 1. Maintain candidate subsequences by linking them through the input sequence.) 15.5 Optimal binary search trees Suppose that we are designing a program to translate text from English to French. For each occurrence of each English word in the text, we need to look up its French equivalent. We could perform these lookup operations by building a binary search tree with n English words as keys and their French equivalents as satellite data. Because we will search the tree for each individual word in the text, we want the total time spent searching to be as low as possible. We could ensure an O.lg n/ search time per occurrence by using a red-black tree or any other balanced binary search tree. Words appear with different frequencies, however, and a frequently used word such as the may appear far from the root while a rarely used word such as machicolation appears near the root. Such an organization would slow down the translation, since the number of nodes visited when searching for a key in a binary search tree equals one plus the depth of the node containing the key. We want words that occur frequently in the text to be placed nearer the root.6 Moreover, some words in the text might have no French translation,7 and such words would not appear in the binary search tree at all. How do we organize a binary search tree so as to minimize the number of nodes visited in all searches, given that we know how often each word occurs? What we need is known as an optimal binary search tree. Formally, we are given a sequence K Dhk1;k2;:::;kni of n distinct keys in sorted order (so that k1 1. b. Suppose now that along with each pixel AŒi; j , we have calculated a real- valued disruption measure dŒi;j, indicating how disruptive it would be to remove pixel AŒi; j . Intuitively, the lower a pixel’s disruption measure, the more similar the pixel is to its neighbors. Suppose further that we deﬁne the disruption measure of a seam to be the sum of the disruption measures of its pixels.410 Chapter 15 Dynamic Programming Give an algorithm to ﬁnd a seam with the lowest disruption measure. How efﬁcient is your algorithm? 15-9 Breaking a string A certain string-processing language allows a programmer to break a string into two pieces. Because this operation copies the string, it costs n time units to break a string of n characters into two pieces. Suppose a programmer wants to break a string into many pieces. The order in which the breaks occur can affect the total amount of time used. For example, suppose that the programmer wants to break a 20-character string after characters 2, 8,and10 (numbering the characters in ascending order from the left-hand end, starting from 1). If she programs the breaks to occur in left-to-right order, then the ﬁrst break costs 20 time units, the second break costs 18 time units (breaking the string from characters 3 to 20 at character 8), and the third break costs 12 time units, totaling 50 time units. If she programs the breaks to occur in right-to-left order, however, then the ﬁrst break costs 20 time units, the second break costs 10 time units, and the third break costs 8 time units, totaling 38 time units. In yet another order, she could break ﬁrst at 8 (costing 20), then break the left piece at 2 (costing 8), and ﬁnally the right piece at 10 (costing 12), for a total cost of 40. Design an algorithm that, given the numbers of characters after which to break, determines a least-cost way to sequence those breaks. More formally, given a string S with n characters and an array LŒ1::mcontaining the break points, com- pute the lowest cost for a sequence of breaks, along with a sequence of breaks that achieves this cost. 15-10 Planning an investment strategy Your knowledge of algorithms helps you obtain an exciting job with the Acme Computer Company, along with a $10,000 signing bonus. You decide to invest this money with the goal of maximizing your return at the end of 10 years. You decide to use the Amalgamated Investment Company to manage your investments. Amalgamated Investments requires you to observe the following rules. It offers n different investments, numbered 1 through n. In each year j , investment i provides a return rate of rij . In other words, if you invest d dollars in investment i in year j , then at the end of year j , you have drij dollars. The return rates are guaranteed, that is, you are given all the return rates for the next 10 years for each investment. You make investment decisions only once per year. At the end of each year, you can leave the money made in the previous year in the same investments, or you can shift money to other investments, by either shifting money between existing investments or moving money to a new investement. If you do not move your money between two consecutive years, you pay a fee of f1 dollars, whereas if you switch your money, you pay a fee of f2 dollars, where f2 >f1.Problems for Chapter 15 411 a. The problem, as stated, allows you to invest your money in multiple investments in each year. Prove that there exists an optimal investment strategy that, in each year, puts all the money into a single investment. (Recall that an optimal investment strategy maximizes the amount of money after 10 years and is not concerned with any other objectives, such as minimizing risk.) b. Prove that the problem of planning your optimal investment strategy exhibits optimal substructure. c. Design an algorithm that plans your optimal investment strategy. What is the running time of your algorithm? d. Suppose that Amalgamated Investments imposed the additional restriction that, at any point, you can have no more than $15,000 in any one investment. Show that the problem of maximizing your income at the end of 10 years no longer exhibits optimal substructure. 15-11 Inventory planning The Rinky Dink Company makes machines that resurface ice rinks. The demand for such products varies from month to month, and so the company needs to de- velop a strategy to plan its manufacturing given the ﬂuctuating, but predictable, demand. The company wishes to design a plan for the next n months. For each month i, the company knows the demand di , that is, the number of machines that it will sell. Let D D Pn iD1 di be the total demand over the next n months. The company keeps a full-time staff who provide labor to manufacture up to m ma- chines per month. If the company needs to make more than m machines in a given month, it can hire additional, part-time labor, at a cost that works out to c dollars per machine. Furthermore, if, at the end of a month, the company is holding any unsold machines, it must pay inventory costs. The cost for holding j machines is given as a function h.j / for j D 1;2;:::;D,whereh.j / 0 for 1 j D and h.j / h.j C 1/ for 1 j D 1. Give an algorithm that calculates a plan for the company that minimizes its costs while fulﬁlling all the demand. The running time should be polyomial in n and D. 15-12 Signing free-agent baseball players Suppose that you are the general manager for a major-league baseball team. During the off-season, you need to sign some free-agent players for your team. The team owner has given you a budget of $X to spend on free agents. You are allowed to spend less than $X altogether, but the owner will ﬁre you if you spend any more than $X.412 Chapter 15 Dynamic Programming You are considering N different positions, and for each position, P free-agent players who play that position are available.8 Because you do not want to overload your roster with too many players at any position, for each position you may sign at most one free agent who plays that position. (If you do not sign any players at a particular position, then you plan to stick with the players you already have at that position.) To determine how valuable a player is going to be, you decide to use a sabermet- ric statistic9 known as “VORP,” or “value over replacement player.” A player with a higher VORP is more valuable than a player with a lower VORP. A player with a higher VORP is not necessarily more expensive to sign than a player with a lower VORP, because factors other than a player’s value determine how much it costs to sign him. For each available free-agent player, you have three pieces of information: the player’s position, the amount of money it will cost to sign the player, and the player’s VORP. Devise an algorithm that maximizes the total VORP of the players you sign while spending no more than $X altogether. You may assume that each player signs for a multiple of $100,000. Your algorithm should output the total VORP of the players you sign, the total amount of money you spend, and a list of which players you sign. Analyze the running time and space requirement of your algorithm. Chapter notes R. Bellman began the systematic study of dynamic programming in 1955. The word “programming,” both here and in linear programming, refers to using a tab- ular solution method. Although optimization techniques incorporating elements of dynamic programming were known earlier, Bellman provided the area with a solid mathematical basis [37]. 8Although there are nine positions on a baseball team, N is not necesarily equal to 9 because some general managers have particular ways of thinking about positions. For example, a general manager might consider right-handed pitchers and left-handed pitchers to be separate “positions,” as well as starting pitchers, long relief pitchers (relief pitchers who can pitch several innings), and short relief pitchers (relief pitchers who normally pitch at most only one inning). 9Sabermetrics is the application of statistical analysis to baseball records. It provides several ways to compare the relative values of individual players.Notes for Chapter 15 413 Galil and Park [125] classify dynamic-programming algorithms according to the size of the table and the number of other table entries each entry depends on. They call a dynamic-programming algorithm tD=eD if its table size is O.nt / and each entry depends on O.ne/ other entries. For example, the matrix-chain multiplication algorithm in Section 15.2 would be 2D=1D, and the longest-common-subsequence algorithm in Section 15.4 would be 2D=0D. Hu and Shing [182, 183] give an O.nlg n/-time algorithm for the matrix-chain multiplication problem. The O.mn/-time algorithm for the longest-common-subsequence problem ap- pears to be a folk algorithm. Knuth [70] posed the question of whether subquadratic algorithms for the LCS problem exist. Masek and Paterson [244] answered this question in the afﬁrmative by giving an algorithm that runs in O.mn=lg n/ time, where n m and the sequences are drawn from a set of bounded size. For the special case in which no element appears more than once in an input sequence, Szymanski [326] shows how to solve the problem in O..n C m/ lg.n C m// time. Many of these results extend to the problem of computing string edit distances (Problem 15-5). An early paper on variable-length binary encodings by Gilbert and Moore [133] had applications to constructing optimal binary search trees for the case in which all probabilities pi are 0; this paper contains an O.n3/-time algorithm. Aho, Hopcroft, and Ullman [5] present the algorithm from Section 15.5. Exercise 15.5-4 is due to Knuth [212]. Hu and Tucker [184] devised an algorithm for the case in which all probabilities pi are 0 that uses O.n2/ time and O.n/ space; subsequently, Knuth [211] reduced the time to O.nlg n/. Problem 15-8 is due to Avidan and Shamir [27], who have posted on the Web a wonderful video illustrating this image-compression technique.16 Greedy Algorithms Algorithms for optimization problems typically go through a sequence of steps, with a set of choices at each step. For many optimization problems, using dynamic programming to determine the best choices is overkill; simpler, more efﬁcient al- gorithms will do. A greedy algorithm always makes the choice that looks best at the moment. That is, it makes a locally optimal choice in the hope that this choice will lead to a globally optimal solution. This chapter explores optimization prob- lems for which greedy algorithms provide optimal solutions. Before reading this chapter, you should read about dynamic programming in Chapter 15, particularly Section 15.3. Greedy algorithms do not always yield optimal solutions, but for many problems they do. We shall ﬁrst examine, in Section 16.1, a simple but nontrivial problem, the activity-selection problem, for which a greedy algorithm efﬁciently computes an optimal solution. We shall arrive at the greedy algorithm by ﬁrst consider- ing a dynamic-programming approach and then showing that we can always make greedy choices to arrive at an optimal solution. Section 16.2 reviews the basic elements of the greedy approach, giving a direct approach for proving greedy al- gorithms correct. Section 16.3 presents an important application of greedy tech- niques: designing data-compression (Huffman) codes. In Section 16.4, we inves- tigate some of the theory underlying combinatorial structures called “matroids,” for which a greedy algorithm always produces an optimal solution. Finally, Sec- tion 16.5 applies matroids to solve a problem of scheduling unit-time tasks with deadlines and penalties. The greedy method is quite powerful and works well for a wide range of prob- lems. Later chapters will present many algorithms that we can view as applica- tions of the greedy method, including minimum-spanning-tree algorithms (Chap- ter 23), Dijkstra’s algorithm for shortest paths from a single source (Chapter 24), and Chv´atal’s greedy set-covering heuristic (Chapter 35). Minimum-spanning-tree algorithms furnish a classic example of the greedy method. Although you can read16.1 An activity-selection problem 415 this chapter and Chapter 23 independently of each other, you might ﬁnd it useful to read them together. 16.1 An activity-selection problem Our ﬁrst example is the problem of scheduling several competing activities that re- quire exclusive use of a common resource, with a goal of selecting a maximum-size set of mutually compatible activities. Suppose we have a set S D fa1;a2;:::;ang of n proposed activities that wish to use a resource, such as a lecture hall, which can serve only one activity at a time. Each activity ai has a start time si and a ﬁnish time fi ,where0 si jAkj j,then we could use A0 kj , rather than Akj , in a solution to the subproblem for Sij .We would have constructed a set of jAikj CjA0 kj jC1>jAikj C jAkj j C 1 D jAij j mutually compatible activities, which contradicts the assumption that Aij is an optimal solution. A symmetric argument applies to the activities in Sik. This way of characterizing optimal substructure suggests that we might solve the activity-selection problem by dynamic programming. If we denote the size of an optimal solution for the set Sij by cŒi;j, then we would have the recurrence cŒi;j D cŒi;k C cŒk;j C 1: Of course, if we did not know that an optimal solution for the set Sij includes activity ak, we would have to examine all activities in Sij to ﬁnd which one to choose, so that cŒi;j D ( 0 if Sij D;; max ak 2Sij fcŒi;k C cŒk;j C 1g if Sij ¤;: (16.2) We could then develop a recursive algorithm and memoize it, or we could work bottom-up and ﬁll in table entries as we go along. But we would be overlooking another important characteristic of the activity-selection problem that we can use to great advantage.16.1 An activity-selection problem 417 Making the greedy choice What if we could choose an activity to add to our optimal solution without having to ﬁrst solve all the subproblems? That could save us from having to consider all the choices inherent in recurrence (16.2). In fact, for the activity-selection problem, we need consider only one choice: the greedy choice. What do we mean by the greedy choice for the activity-selection problem? Intu- ition suggests that we should choose an activity that leaves the resource available for as many other activities as possible. Now, of the activities we end up choos- ing, one of them must be the ﬁrst one to ﬁnish. Our intuition tells us, therefore, to choose the activity in S with the earliest ﬁnish time, since that would leave the resource available for as many of the activities that follow it as possible. (If more than one activity in S has the earliest ﬁnish time, then we can choose any such activity.) In other words, since the activities are sorted in monotonically increasing order by ﬁnish time, the greedy choice is activity a1. Choosing the ﬁrst activity to ﬁnish is not the only way to think of making a greedy choice for this problem; Exercise 16.1-3 asks you to explore other possibilities. If we make the greedy choice, we have only one remaining subproblem to solve: ﬁnding activities that start after a1 ﬁnishes. Why don’t we have to consider ac- tivities that ﬁnish before a1 starts? We have that s1 n, in which case we have examined all activities in Sk without ﬁnding one that is compatible with ak. In this case, Sk D;,andsothe procedure returns ; in line 6. Assuming that the activities have already been sorted by ﬁnish times, the running time of the call RECURSIVE-ACTIVITY-SELECTOR.s;f;0;n/ is ‚.n/,whichwe can see as follows. Over all recursive calls, each activity is examined exactly once in the while loop test of line 2. In particular, activity ai is examined in the last call made in which k jAj.Thatis,A and B are acyclic sets of edges, and B contains more edges than A does. We claim that a forest F D .VF ;EF / contains exactly jVF j jEF j trees. To see why, suppose that F consists of t trees, where the ith tree contains i vertices and ei edges. Then, we have jEF j D tX iD1 ei D tX iD1 .i 1/ (by Theorem B.2) D tX iD1 i t D jVF j t; which implies that t D jVF j jEF j. Thus, forest GA contains jV j jAj trees, and forest GB contains jV j jBj trees. Since forest GB has fewer trees than forest GA does, forest GB must contain some tree T whose vertices are in two different trees in forest GA. Moreover, since T is connected, it must contain an edge .u; / such that vertices u and are in different trees in forest GA. Since the edge .u; / connects vertices in two different trees in forest GA, we can add the edge .u; / to forest GA without creating a cycle. Therefore, MG satisﬁes the exchange property, completing the proof that MG is a matroid. Given a matroid M D .S; /, we call an element x … A an extension of A 2 if we can add x to A while preserving independence; that is, x is an extension of A if A [ fxg 2 . As an example, consider a graphic matroid MG.IfA is an independent set of edges, then edge e is an extension of A if and only if e is not in A and the addition of e to A does not create a cycle. If A is an independent subset in a matroid M, we say that A is maximal if it has no extensions. That is, A is maximal if it is not contained in any larger independent subset of M. The following property is often useful.16.4 Matroids and greedy methods 439 Theorem 16.6 All maximal independent subsets in a matroid have the same size. Proof Suppose to the contrary that A is a maximal independent subset of M and there exists another larger maximal independent subset B of M. Then, the exchange property implies that for some x 2 B A, we can extend A to a larger independent set A [ fxg, contradicting the assumption that A is maximal. As an illustration of this theorem, consider a graphic matroid MG for a con- nected, undirected graph G. Every maximal independent subset of MG must be a free tree with exactly jV j 1 edges that connects all the vertices of G. Such a tree is called a spanning tree of G. We say that a matroid M D .S; / is weighted if it is associated with a weight function w that assigns a strictly positive weight w.x/ to each element x 2 S.The weight function w extends to subsets of S by summation: w.A/ D X x2A w.x/ for any A S. For example, if we let w.e/ denote the weight of an edge e in a graphic matroid MG,thenw.A/ is the total weight of the edges in edge set A. Greedy algorithms on a weighted matroid Many problems for which a greedy approach provides optimal solutions can be for- mulated in terms of ﬁnding a maximum-weight independent subset in a weighted matroid. That is, we are given a weighted matroid M D .S; /, and we wish to ﬁnd an independent set A 2 such that w.A/ is maximized. We call such a sub- set that is independent and has maximum possible weight an optimal subset of the matroid. Because the weight w.x/ of any element x 2 S is positive, an optimal subset is always a maximal independent subset—it always helps to make A as large as possible. For example, in the minimum-spanning-tree problem, we are given a connected undirected graph G D .V; E/ and a length function w such that w.e/ is the (posi- tive) length of edge e. (We use the term “length” here to refer to the original edge weights for the graph, reserving the term “weight” to refer to the weights in the associated matroid.) We wish to ﬁnd a subset of the edges that connects all of the vertices together and has minimum total length. To view this as a problem of ﬁnding an optimal subset of a matroid, consider the weighted matroid MG with weight function w0,wherew0.e/ D w0 w.e/ and w0 is larger than the maximum length of any edge. In this weighted matroid, all weights are positive and an opti- mal subset is a spanning tree of minimum total length in the original graph. More speciﬁcally, each maximal independent subset A corresponds to a spanning tree440 Chapter 16 Greedy Algorithms with jV j 1 edges, and since w0.A/ D X e2A w0.e/ D X e2A .w0 w.e// D .jV j 1/w0 X e2A w.e/ D .jV j 1/w0 w.A/ for any maximal independent subset A, an independent subset that maximizes the quantity w0.A/ must minimize w.A/. Thus, any algorithm that can ﬁnd an optimal subset A in an arbitrary matroid can solve the minimum-spanning-tree problem. Chapter 23 gives algorithms for the minimum-spanning-tree problem, but here we give a greedy algorithm that works for any weighted matroid. The algorithm takes as input a weighted matroid M D .S; / with an associated positive weight function w, and it returns an optimal subset A. In our pseudocode, we denote the components of M by M:S and M: and the weight function by w. The algorithm is greedy because it considers in turn each element x 2 S, in order of monotoni- cally decreasing weight, and immediately adds it to the set A being accumulated if A [ fxg is independent. GREEDY.M; w/ 1 A D; 2sortM:S into monotonically decreasing order by weight w 3 for each x 2 M:S, taken in monotonically decreasing order by weight w.x/ 4 if A [ fxg 2 M: 5 A D A [ fxg 6 return A Line 4 checks whether adding each element x to A would maintain A as an inde- pendent set. If A would remain independent, then line 5 adds x to A. Otherwise, x is discarded. Since the empty set is independent, and since each iteration of the for loop maintains A’s independence, the subset A is always independent, by induc- tion. Therefore, GREEDY always returns an independent subset A. We shall see in a moment that A is a subset of maximum possible weight, so that A is an optimal subset. The running time of GREEDY is easy to analyze. Let n denote jSj. The sorting phase of GREEDY takes time O.nlg n/. Line 4 executes exactly n times, once for each element of S. Each execution of line 4 requires a check on whether or not the set A [ fxg is independent. If each such check takes time O.f .n//, the entire algorithm runs in time O.nlg n C nf.n//.16.4 Matroids and greedy methods 441 We now prove that GREEDY returns an optimal subset. Lemma 16.7 (Matroids exhibit the greedy-choice property) Suppose that M D .S; / is a weighted matroid with weight function w and that S is sorted into monotonically decreasing order by weight. Let x be the ﬁrst element of S such that fxg is independent, if any such x exists. If x exists, then there exists an optimal subset A of S that contains x. Proof If no such x exists, then the only independent subset is the empty set and the lemma is vacuously true. Otherwise, let B be any nonempty optimal subset. Assume that x … B; otherwise, letting A D B gives an optimal subset of S that contains x. No element of B has weight greater than w.x/. To see why, observe that y 2 B implies that fyg is independent, since B 2 and is hereditary. Our choice of x therefore ensures that w.x/ w.y/ for any y 2 B. Construct the set A as follows. Begin with A D fxg. By the choice of x, set A is independent. Using the exchange property, repeatedly ﬁnd a new element of B that we can add to A until jAj D jBj, while preserving the independence of A.Atthat point, A and B are the same except that A has x and B has some other element y. That is, A D B fyg [ fxg for some y 2 B,andso w.A/ D w.B/ w.y/ C w.x/ w.B/ : Because set B is optimal, set A, which contains x, must also be optimal. We next show that if an element is not an option initially, then it cannot be an option later. Lemma 16.8 Let M D .S; / be any matroid. If x is an element of S that is an extension of some independent subset A of S,thenx is also an extension of ;. Proof Since x is an extension of A,wehavethatA[fxg is independent. Since is hereditary, fxg must be independent. Thus, x is an extension of ;. Corollary 16.9 Let M D .S; / be any matroid. If x is an element of S such that x is not an extension of ;,thenx is not an extension of any independent subset A of S. Proof This corollary is simply the contrapositive of Lemma 16.8.442 Chapter 16 Greedy Algorithms Corollary 16.9 says that any element that cannot be used immediately can never be used. Therefore, GREEDY cannot make an error by passing over any initial elements in S that are not an extension of ;, since they can never be used. Lemma 16.10 (Matroids exhibit the optimal-substructure property) Let x be the ﬁrst element of S chosen by GREEDY for the weighted matroid M D .S; /. The remaining problem of ﬁnding a maximum-weight indepen- dent subset containing x reduces to ﬁnding a maximum-weight independent subset of the weighted matroid M 0 D .S0; 0/,where S 0 D fy 2 S W fx;yg 2 g ; 0 D fB S fxg W B [ fxg 2 g ; and the weight function for M 0 is the weight function for M, restricted to S 0.(We call M 0 the contraction of M by the element x.) Proof If A is any maximum-weight independent subset of M containing x,then A0 D A fxg is an independent subset of M 0. Conversely, any independent sub- set A0 of M 0 yields an independent subset A D A0 [ fxg of M. Since we have in both cases that w.A/ D w.A0/Cw.x/, a maximum-weight solution in M contain- ing x yields a maximum-weight solution in M 0, and vice versa. Theorem 16.11 (Correctness of the greedy algorithm on matroids) If M D .S; / is a weighted matroid with weight function w,thenGREEDY.M; w/ returns an optimal subset. Proof By Corollary 16.9, any elements that GREEDY passes over initially be- cause they are not extensions of ; can be forgotten about, since they can never be useful. Once GREEDY selects the ﬁrst element x, Lemma 16.7 implies that the algorithm does not err by adding x to A, since there exists an optimal subset containing x. Finally, Lemma 16.10 implies that the remaining problem is one of ﬁnding an optimal subset in the matroid M 0 that is the contraction of M by x. After the procedure GREEDY sets A to fxg, we can interpret all of its remaining steps as acting in the matroid M 0 D .S0; 0/, because B is independent in M 0 if and only if B [ fxg is independent in M, for all sets B 2 0. Thus, the subsequent operation of GREEDY will ﬁnd a maximum-weight independent subset for M 0,and the overall operation of GREEDY will ﬁnd a maximum-weight independent subset for M.16.5 A task-scheduling problem as a matroid 443 Exercises 16.4-1 Show that .S; k / is a matroid, where S is any ﬁnite set and k is the set of all subsets of S of size at most k,wherek jSj. 16.4-2 ? Given an m n matrix T over some ﬁeld (such as the reals), show that .S; / is a matroid, where S is the set of columns of T and A 2 if and only if the columns in A are linearly independent. 16.4-3 ? Show that if .S; / is a matroid, then .S; 0/ is a matroid, where 0 D fA0 W S A0 contains some maximal A 2 g : That is, the maximal independent sets of .S; 0/ are just the complements of the maximal independent sets of .S; /. 16.4-4 ? Let S be a ﬁnite set and let S1;S2;:::;Sk be a partition of S into nonempty disjoint subsets. Deﬁne the structure .S; / by the condition that D fA W jA \ Si j 1 for i D 1;2;:::;kg. Show that .S; / is a matroid. That is, the set of all sets A that contain at most one member of each subset in the partition determines the independent sets of a matroid. 16.4-5 Show how to transform the weight function of a weighted matroid problem, where the desired optimal solution is a minimum-weight maximal independent subset, to make it a standard weighted-matroid problem. Argue carefully that your transfor- mation is correct. ? 16.5 A task-scheduling problem as a matroid An interesting problem that we can solve using matroids is the problem of op- timally scheduling unit-time tasks on a single processor, where each task has a deadline, along with a penalty paid if the task misses its deadline. The problem looks complicated, but we can solve it in a surprisingly simple manner by casting it as a matroid and using a greedy algorithm. A unit-time task is a job, such as a program to be run on a computer, that requires exactly one unit of time to complete. Given a ﬁnite set S of unit-time tasks, a444 Chapter 16 Greedy Algorithms schedule for S is a permutation of S specifying the order in which to perform these tasks. The ﬁrst task in the schedule begins at time 0 and ﬁnishes at time 1, the second task begins at time 1 and ﬁnishes at time 2, and so on. The problem of scheduling unit-time tasks with deadlines and penalties for a single processor has the following inputs: a set S D fa1;a2;:::;ang of n unit-time tasks; a set of n integer deadlines d1;d2;:::;dn, such that each di satisﬁes 1 di n and task ai is supposed to ﬁnish by time di ;and a set of n nonnegative weights or penalties w1;w2;:::;wn, such that we incur a penalty of wi if task ai is not ﬁnished by time di , and we incur no penalty if a task ﬁnishes by its deadline. We wish to ﬁnd a schedule for S that minimizes the total penalty incurred for missed deadlines. Consider a given schedule. We say that a task is late in this schedule if it ﬁnishes after its deadline. Otherwise, the task is early in the schedule. We can always trans- form an arbitrary schedule into early-ﬁrst form, in which the early tasks precede the late tasks. To see why, note that if some early task ai follows some late task aj , then we can switch the positions of ai and aj ,andai will still be early and aj will still be late. Furthermore, we claim that we can always transform an arbitrary schedule into canonical form, in which the early tasks precede the late tasks and we schedule the early tasks in order of monotonically increasing deadlines. To do so, we put the schedule into early-ﬁrst form. Then, as long as there exist two early tasks ai and aj ﬁnishing at respective times k and k C 1 in the schedule such that dj t for some t, then there is no way to make a schedule with no late tasks for set A, because more than t tasks must ﬁnish before time t. Therefore, (1) implies (2). If (2) holds, then (3) must follow: there is no way to “get stuck” when scheduling the tasks in order of monotonically increasing deadlines, since (2) implies that the ith largest deadline is at least i. Finally, (3) trivially implies (1). Using property 2 of Lemma 16.12, we can easily compute whether or not a given set of tasks is independent (see Exercise 16.5-2). The problem of minimizing the sum of the penalties of the late tasks is the same as the problem of maximizing the sum of the penalties of the early tasks. The following theorem thus ensures that we can use the greedy algorithm to ﬁnd an independent set A of tasks with the maximum total penalty. Theorem 16.13 If S is a set of unit-time tasks with deadlines, and is the set of all independent sets of tasks, then the corresponding system .S; / is a matroid. Proof Every subset of an independent set of tasks is certainly independent. To prove the exchange property, suppose that B and A are independent sets of tasks and that jBj > jAj.Letk be the largest t such that Nt .B/ Nt .A/. (Such a value of t exists, since N0.A/ D N0.B/ D 0.) Since Nn.B/ D jBj and Nn.A/ D jAj, but jBj > jAj, we must have that k Nj .A/ for all j in the range k C 1 j n. Therefore, B contains more tasks with deadline k C 1 than A does. Let ai be a task in B A with deadline k C 1.LetA0 D A [ fai g. We now show that A0 must be independent by using property 2 of Lemma 16.12. For 0 t k,wehaveNt .A0/ D Nt .A/ t,sinceA is independent. For k1and k 1. Show that the greedy algorithm always yields an optimal solution. c. Give a set of coin denominations for which the greedy algorithm does not yield an optimal solution. Your set should include a penny so that there is a solution for every value of n. d. Give an O.nk/-time algorithm that makes change for any set of k different coin denominations, assuming that one of the coins is a penny. 16-2 Scheduling to minimize average completion time Suppose you are given a set S D fa1;a2;:::;ang of tasks, where task ai re- quires pi units of processing time to complete, once it has started. You have one computer on which to run these tasks, and the computer can run only one task at a time. Let ci be the completion time of task ai , that is, the time at which task ai com- pletes processing. Your goal is to minimize the average completion time, that is, to minimize .1=n/ Pn iD1 ci . For example, suppose there are two tasks, a1 and a2, with p1 D 3 and p2 D 5, and consider the schedule in which a2 runs ﬁrst, followed by a1.Thenc2 D 5, c1 D 8, and the average completion time is .5 C 8/=2 D 6:5. If task a1 runs ﬁrst, however, then c1 D 3, c2 D 8, and the average completion time is .3 C 8/=2 D 5:5. a. Give an algorithm that schedules the tasks so as to minimize the average com- pletion time. Each task must run non-preemptively, that is, once task ai starts, it must run continuously for pi units of time. Prove that your algorithm minimizes the average completion time, and state the running time of your algorithm. b. Suppose now that the tasks are not all available at once. That is, each task cannot start until its release time ri . Suppose also that we allow preemption,so that a task can be suspended and restarted at a later time. For example, a task ai with processing time pi D 6 and release time ri D 1 might start running at time 1 and be preempted at time 4. It might then resume at time 10 but be preempted at time 11, and it might ﬁnally resume at time 13 and complete at time 15. Task ai has run for a total of 6 time units, but its running time has been divided into three pieces. In this scenario, ai ’s completion time is 15.Give an algorithm that schedules the tasks so as to minimize the average completion time in this new scenario. Prove that your algorithm minimizes the average completion time, and state the running time of your algorithm.448 Chapter 16 Greedy Algorithms 16-3 Acyclic subgraphs a. The incidence matrix for an undirected graph G D .V; E/ is a jV j jEj ma- trix M such that Me D 1 if edge e is incident on vertex ,andMe D 0 other- wise. Argue that a set of columns of M is linearly independent over the ﬁeld of integers modulo 2 if and only if the corresponding set of edges is acyclic. Then, use the result of Exercise 16.4-2 to provide an alternate proof that .E; / of part (a) is a matroid. b. Suppose that we associate a nonnegative weight w.e/ with each edge in an undirected graph G D .V; E/. Give an efﬁcient algorithm to ﬁnd an acyclic subset of E of maximum total weight. c. Let G.V; E/ be an arbitrary directed graph, and let .E; / be deﬁned so that A 2 if and only if A does not contain any directed cycles. Give an example of a directed graph G such that the associated system .E; / is not a matroid. Specify which deﬁning condition for a matroid fails to hold. d. The incidence matrix for a directed graph G D .V; E/ with no self-loops is a jV j jEj matrix M such that Me D1 if edge e leaves vertex , Me D 1 if edge e enters vertex ,andMe D 0 otherwise. Argue that if a set of columns of M is linearly independent, then the corresponding set of edges does not contain a directed cycle. e. Exercise 16.4-2 tells us that the set of linearly independent sets of columns of any matrix M forms a matroid. Explain carefully why the results of parts (d) and (e) are not contradictory. How can there fail to be a perfect correspon- dence between the notion of a set of edges being acyclic and the notion of the associated set of columns of the incidence matrix being linearly independent? 16-4 Scheduling variations Consider the following algorithm for the problem from Section 16.5 of scheduling unit-time tasks with deadlines and penalties. Let all n time slots be initially empty, where time slot i is the unit-length slot of time that ﬁnishes at time i. We consider the tasks in order of monotonically decreasing penalty. When considering task aj , if there exists a time slot at or before aj ’s deadline dj that is still empty, assign aj to the latest such slot, ﬁlling it. If there is no such slot, assign task aj to the latest of the as yet unﬁlled slots. a. Argue that this algorithm always gives an optimal answer. b. Use the fast disjoint-set forest presented in Section 21.3 to implement the algo- rithm efﬁciently. Assume that the set of input tasks has already been sorted intoProblems for Chapter 16 449 monotonically decreasing order by penalty. Analyze the running time of your implementation. 16-5 Off-line caching Modern computers use a cache to store a small amount of data in a fast memory. Even though a program may access large amounts of data, by storing a small subset of the main memory in the cache—a small but faster memory—overall access time can greatly decrease. When a computer program executes, it makes a sequence hr1;r2;:::;rni of n memory requests, where each request is for a particular data element. For example, a program that accesses 4 distinct elements fa; b; c; dg might make the sequence of requests hd; b; d; b; d; a; c; d; b; a; c; bi.Letk be the size of the cache. When the cache contains k elements and the program requests the .k C 1/st element, the system must decide, for this and each subsequent request, which k elements to keep in the cache. More precisely, for each request ri ,the cache-management algorithm checks whether element ri is already in the cache. If it is, then we have a cache hit; otherwise, we have a cache miss. Upon a cache miss, the system retrieves ri from the main memory, and the cache-management algorithm must decide whether to keep ri in the cache. If it decides to keep ri and the cache already holds k elements, then it must evict one element to make room for ri . The cache-management algorithm evicts data with the goal of minimizing the number of cache misses over the entire sequence of requests. Typically, caching is an on-line problem. That is, we have to make decisions about which data to keep in the cache without knowing the future requests. Here, however, we consider the off-line version of this problem, in which we are given in advance the entire sequence of n requests and the cache size k, and we wish to minimize the total number of cache misses. We can solve this off-line problem by a greedy strategy called furthest-in-future, which chooses to evict the item in the cache whose next access in the request sequence comes furthest in the future. a. Write pseudocode for a cache manager that uses the furthest-in-future strategy. The input should be a sequence hr1;r2;:::;rni of requests and a cache size k, and the output should be a sequence of decisions about which data element (if any) to evict upon each request. What is the running time of your algorithm? b. Show that the off-line caching problem exhibits optimal substructure. c. Prove that furthest-in-future produces the minimum possible number of cache misses.450 Chapter 16 Greedy Algorithms Chapter notes Much more material on greedy algorithms and matroids can be found in Lawler [224] and Papadimitriou and Steiglitz [271]. The greedy algorithm ﬁrst appeared in the combinatorial optimization literature in a 1971 article by Edmonds [101], though the theory of matroids dates back to a 1935 article by Whitney [355]. Our proof of the correctness of the greedy algorithm for the activity-selection problem is based on that of Gavril [131]. The task-scheduling problem is studied in Lawler [224]; Horowitz, Sahni, and Rajasekaran [181]; and Brassard and Bratley [54]. Huffman codes were invented in 1952 [185]; Lelewer and Hirschberg [231] sur- veys data-compression techniques known as of 1987. An extension of matroid theory to greedoid theory was pioneered by Korte and Lov´asz [216, 217, 218, 219], who greatly generalize the theory presented here.17 Amortized Analysis In an amortized analysis, we average the time required to perform a sequence of data-structure operations over all the operations performed. With amortized analy- sis, we can show that the average cost of an operation is small, if we average over a sequence of operations, even though a single operation within the sequence might be expensive. Amortized analysis differs from average-case analysis in that prob- ability is not involved; an amortized analysis guarantees the average performance of each operation in the worst case. The ﬁrst three sections of this chapter cover the three most common techniques used in amortized analysis. Section 17.1 starts with aggregate analysis, in which we determine an upper bound T .n/ on the total cost of a sequence of n operations. The average cost per operation is then T .n/=n. We take the average cost as the amortized cost of each operation, so that all operations have the same amortized cost. Section 17.2 covers the accounting method, in which we determine an amortized cost of each operation. When there is more than one type of operation, each type of operation may have a different amortized cost. The accounting method overcharges some operations early in the sequence, storing the overcharge as “prepaid credit” on speciﬁc objects in the data structure. Later in the sequence, the credit pays for operations that are charged less than they actually cost. Section 17.3 discusses the potential method, which is like the accounting method in that we determine the amortized cost of each operation and may overcharge op- erations early on to compensate for undercharges later. The potential method main- tains the credit as the “potential energy” of the data structure as a whole instead of associating the credit with individual objects within the data structure. We shall use two examples to examine these three methods. One is a stack with the additional operation MULTIPOP, which pops several objects at once. The other is a binary counter that counts up from 0 by means of the single operation INCREMENT.452 Chapter 17 Amortized Analysis While reading this chapter, bear in mind that the charges assigned during an amortized analysis are for analysis purposes only. They need not—and should not—appear in the code. If, for example, we assign a credit to an object x when using the accounting method, we have no need to assign an appropriate amount to some attribute, such as x:credit, in the code. When we perform an amortized analysis, we often gain insight into a particular data structure, and this insight can help us optimize the design. In Section 17.4, for example, we shall use the potential method to analyze a dynamically expanding and contracting table. 17.1 Aggregate analysis In aggregate analysis, we show that for all n, a sequence of n operations takes worst-case time T .n/ in total. In the worst case, the average cost, or amortized cost, per operation is therefore T .n/=n. Note that this amortized cost applies to each operation, even when there are several types of operations in the sequence. The other two methods we shall study in this chapter, the accounting method and the potential method, may assign different amortized costs to different types of operations. Stack operations In our ﬁrst example of aggregate analysis, we analyze stacks that have been aug- mented with a new operation. Section 10.1 presented the two fundamental stack operations, each of which takes O.1/ time: PUSH.S; x/ pushes object x onto stack S. POP.S/ pops the top of stack S and returns the popped object. Calling POP on an empty stack generates an error. Since each of these operations runs in O.1/ time, let us consider the cost of each to be 1. The total cost of a sequence of n PUSH and POP operations is therefore n, and the actual running time for n operations is therefore ‚.n/. Now we add the stack operation MULTIPOP.S; k/, which removes the k top ob- jects of stack S, popping the entire stack if the stack contains fewer than k objects. Of course, we assume that k is positive; otherwise the MULTIPOP operation leaves the stack unchanged. In the following pseudocode, the operation STACK-EMPTY returns TRUE if there are no objects currently on the stack, and FALSE otherwise.17.1 Aggregate analysis 453 23 17 6 39 10 47 (a) top 10 47 (b) top (c) Figure 17.1 The action of MULTIPOP on a stack S, shown initially in (a).Thetop4 objects are popped by MULTIPOP.S; 4/, whose result is shown in (b). The next operation is MULTIPOP.S; 7/, which empties the stack—shown in (c)—since there were fewer than 7 objects remaining. MULTIPOP.S; k/ 1 while not STACK-EMPTY.S/ and k>0 2POP.S/ 3 k D k 1 Figure 17.1 shows an example of MULTIPOP. What is the running time of MULTIPOP.S; k/ on a stack of s objects? The actual running time is linear in the number of POP operations actually executed, and thus we can analyze MULTIPOP in terms of the abstract costs of 1 each for PUSH and POP. The number of iterations of the while loop is the number min.s; k/ of objects popped off the stack. Each iteration of the loop makes one call to POP in line 2. Thus, the total cost of MULTIPOP is min.s; k/, and the actual running time is a linear function of this cost. Let us analyze a sequence of n PUSH,POP,andMULTIPOP operations on an ini- tially empty stack. The worst-case cost of a MULTIPOP operation in the sequence is O.n/, since the stack size is at most n. The worst-case time of any stack opera- tion is therefore O.n/, and hence a sequence of n operations costs O.n2/,sincewe may have O.n/ MULTIPOP operations costing O.n/ each. Although this analysis is correct, the O.n2/ result, which we obtained by considering the worst-case cost of each operation individually, is not tight. Using aggregate analysis, we can obtain a better upper bound that considers the entire sequence of n operations. In fact, although a single MULTIPOP operation can be expensive, any sequence of n PUSH,POP,andMULTIPOP operations on an initially empty stack can cost at most O.n/. Why? We can pop each object from the stack at most once for each time we have pushed it onto the stack. Therefore, the number of times that POP can be called on a nonempty stack, including calls within MULTIPOP, is at most the number of PUSH operations, which is at most n.Forany value of n, any sequence of n PUSH,POP,andMULTIPOP operations takes a total of O.n/ time. The average cost of an operation is O.n/=n D O.1/. In aggregate454 Chapter 17 Amortized Analysis analysis, we assign the amortized cost of each operation to be the average cost. In this example, therefore, all three stack operations have an amortized cost of O.1/. We emphasize again that although we have just shown that the average cost, and hence the running time, of a stack operation is O.1/, we did not use probabilistic reasoning. We actually showed a worst-case bound of O.n/ on a sequence of n operations. Dividing this total cost by n yielded the average cost per operation, or the amortized cost. Incrementing a binary counter As another example of aggregate analysis, consider the problem of implementing a k-bit binary counter that counts upward from 0. We use an array AŒ0 : : k 1 of bits, where A:length D k, as the counter. A binary number x that is stored in the counter has its lowest-order bit in AŒ0 and its highest-order bit in AŒk 1,sothat x D Pk1 iD0 AŒi 2i . Initially, x D 0, and thus AŒi D 0 for i D 0; 1; : : : ; k 1.To add 1 (modulo 2k) to the value in the counter, we use the following procedure. INCREMENT.A/ 1 i D 0 2 while i0,thenbi D bi1 ti C 1. In either case, bi bi1 ti C 1,andthe potential difference is ˆ.Di / ˆ.Di1/ .bi1 ti C 1/ bi1 D 1 ti : The amortized cost is therefore yci D ci C ˆ.Di / ˆ.Di1/ .ti C 1/ C .1 ti / D 2: If the counter starts at zero, then ˆ.D0/ D 0.Sinceˆ.Di / 0 for all i, the total amortized cost of a sequence of n INCREMENT operations is an upper bound on the total actual cost, and so the worst-case cost of n INCREMENT operations is O.n/. The potential method gives us an easy way to analyze the counter even when it does not start at zero. The counter starts with b0 1s, and after n INCREMENT462 Chapter 17 Amortized Analysis operations it has bn 1s, where 0 b0;bn k. (Recall that k is the number of bits in the counter.) We can rewrite equation (17.3) as nX iD1 ci D nX iD1 yci ˆ.Dn/ C ˆ.D0/: (17.4) We have yci 2 for all 1 i n.Sinceˆ.D0/ D b0 and ˆ.Dn/ D bn, the total actual cost of n INCREMENT operations is nX iD1 ci nX iD1 2 bn C b0 D 2n bn C b0 : Note in particular that since b0 k, as long as k D O.n/, the total actual cost is O.n/. In other words, if we execute at least n D .k/ INCREMENT operations, the total actual cost is O.n/, no matter what initial value the counter contains. Exercises 17.3-1 Suppose we have a potential function ˆ such that ˆ.Di / ˆ.D0/ for all i,but ˆ.D0/ ¤ 0. Show that there exists a potential function ˆ0 such that ˆ0.D0/ D 0, ˆ0.Di / 0 for all i 1, and the amortized costs using ˆ0 are the same as the amortized costs using ˆ. 17.3-2 Redo Exercise 17.1-3 using a potential method of analysis. 17.3-3 Consider an ordinary binary min-heap data structure with n elements supporting the instructions INSERT and EXTRACT-MIN in O.lg n/ worst-case time. Give a potential function ˆ such that the amortized cost of INSERT is O.lg n/ and the amortized cost of EXTRACT-MIN is O.1/, and show that it works. 17.3-4 What is the total cost of executing n of the stack operations PUSH,POP,and MULTIPOP, assuming that the stack begins with s0 objects and ﬁnishes with sn objects? 17.3-5 Suppose that a counter begins at a number with b1s in its binary representa- tion, rather than at 0. Show that the cost of performing n INCREMENT operations is O.n/ if n D .b/. (Do not assume that b is constant.)17.4 Dynamic tables 463 17.3-6 Show how to implement a queue with two ordinary stacks (Exercise 10.1-6) so that the amortized cost of each ENQUEUE and each DEQUEUE operation is O.1/. 17.3-7 Design a data structure to support the following two operations for a dynamic multiset S of integers, which allows duplicate values: INSERT.S; x/ inserts x into S. DELETE-LARGER-HALF.S/ deletes the largest djSj =2e elements from S. Explain how to implement this data structure so that any sequence of m INSERT and DELETE-LARGER-HALF operations runs in O.m/ time. Your implementation should also include a way to output the elements of S in O.jSj/ time. 17.4 Dynamic tables We do not always know in advance how many objects some applications will store in a table. We might allocate space for a table, only to ﬁnd out later that it is not enough. We must then reallocate the table with a larger size and copy all objects stored in the original table over into the new, larger table. Similarly, if many objects have been deleted from the table, it may be worthwhile to reallocate the table with a smaller size. In this section, we study this problem of dynamically expanding and contracting a table. Using amortized analysis, we shall show that the amortized cost of insertion and deletion is only O.1/, even though the actual cost of an operation is large when it triggers an expansion or a contraction. Moreover, we shall see how to guarantee that the unused space in a dynamic table never exceeds a constant fraction of the total space. We assume that the dynamic table supports the operations TABLE-INSERT and TABLE-DELETE.TABLE-INSERT inserts into the table an item that occupies a sin- gle slot, that is, a space for one item. Likewise, TABLE-DELETE removes an item from the table, thereby freeing a slot. The details of the data-structuring method used to organize the table are unimportant; we might use a stack (Section 10.1), a heap (Chapter 6), or a hash table (Chapter 11). We might also use an array or collection of arrays to implement object storage, as we did in Section 10.3. We shall ﬁnd it convenient to use a concept introduced in our analysis of hashing (Chapter 11). We deﬁne the load factor ˛.T / of a nonempty table T to be the number of items stored in the table divided by the size (number of slots) of the table. We assign an empty table (one with no items) size 0, and we deﬁne its load factor to be 1. If the load factor of a dynamic table is bounded below by a constant,464 Chapter 17 Amortized Analysis the unused space in the table is never more than a constant fraction of the total amount of space. We start by analyzing a dynamic table in which we only insert items. We then consider the more general case in which we both insert and delete items. 17.4.1 Table expansion Let us assume that storage for a table is allocated as an array of slots. A table ﬁlls up when all slots have been used or, equivalently, when its load factor is 1.1 In some software environments, upon attempting to insert an item into a full table, the only alternative is to abort with an error. We shall assume, however, that our software environment, like many modern ones, provides a memory-management system that can allocate and free blocks of storage on request. Thus, upon inserting an item into a full table, we can expand the table by allocating a new table with more slots than the old table had. Because we always need the table to reside in contiguous memory, we must allocate a new array for the larger table and then copy items from the old table into the new table. A common heuristic allocates a new table with twice as many slots as the old one. If the only table operations are insertions, then the load factor of the table is always at least 1=2, and thus the amount of wasted space never exceeds half the total space in the table. In the following pseudocode, we assume that T is an object representing the table. The attribute T:table contains a pointer to the block of storage representing the table, T:num contains the number of items in the table, and T:size gives the total number of slots in the table. Initially, the table is empty: T:num D T:size D 0. TABLE-INSERT.T; x/ 1 if T:size == 0 2 allocate T:table with 1 slot 3 T:size D 1 4 if T:num == T:size 5 allocate new-table with 2 T:size slots 6 insert all items in T:table into new-table 7 free T:table 8 T:table D new-table 9 T:size D 2 T:size 10 insert x into T:table 11 T:num D T:num C 1 1In some situations, such as an open-address hash table, we may wish to consider a table to be full if its load factor equals some constant strictly less than 1.(SeeExercise17.4-1.)17.4 Dynamic tables 465 Notice that we have two “insertion” procedures here: the TABLE-INSERT proce- dure itself and the elementary insertion into a table in lines 6 and 10. We can analyze the running time of TABLE-INSERT in terms of the number of elementary insertions by assigning a cost of 1 to each elementary insertion. We assume that the actual running time of TABLE-INSERT is linear in the time to insert individual items, so that the overhead for allocating an initial table in line 2 is constant and the overhead for allocating and freeing storage in lines 5 and 7 is dominated by the cost of transferring items in line 6. We call the event in which lines 5–9 are executed an expansion. Let us analyze a sequence of n TABLE-INSERT operations on an initially empty table. What is the cost ci of the ith operation? If the current table has room for the new item (or if this is the ﬁrst operation), then ci D 1, since we need only perform the one elementary insertion in line 10. If the current table is full, however, and an expansion occurs, then ci D i: the cost is 1 for the elementary insertion in line 10 plus i 1 for the items that we must copy from the old table to the new table in line 6. If we perform n operations, the worst-case cost of an operation is O.n/, which leads to an upper bound of O.n2/ on the total running time for n operations. This bound is not tight, because we rarely expand the table in the course of n TABLE-INSERT operations. Speciﬁcally, the ith operation causes an expansion only when i 1 is an exact power of 2. The amortized cost of an operation is in fact O.1/, as we can show using aggregate analysis. The cost of the ith operation is ci D ( i if i 1 is an exact power of 2; 1 otherwise : The total cost of n TABLE-INSERT operations is therefore nX iD1 ci n C blg ncX jD0 2j x:keyi 3 i D i C 1 4 if i x:n and k == x:keyi 5 return .x; i/ 6 elseif x:leaf 7 return NIL 8 else DISK-READ.x:ci / 9 return B-TREE-SEARCH.x:ci;k/ Using a linear-search procedure, lines 1–3 ﬁnd the smallest index i such that k x:keyi , or else they set i to x:n C 1. Lines 4–5 check to see whether we have now discovered the key, returning if we have. Otherwise, lines 6–9 either ter- minate the search unsuccessfully (if x is a leaf) or recurse to search the appropriate subtree of x, after performing the necessary DISK-READ on that child. Figure 18.1 illustrates the operation of B-TREE-SEARCH. The procedure exam- ines the lightly shaded nodes during a search for the key R. As in the TREE-SEARCH procedure for binary search trees, the nodes encoun- tered during the recursion form a simple path downward from the root of the tree. The B-TREE-SEARCH procedure therefore accesses O.h/ D O.logt n/ disk pages, where h is the height of the B-tree and n is the number of keys in the B-tree. Since x:n <2t,thewhile loop of lines 2–3 takes O.t/ time within each node, and the total CPU time is O.th/ D O.t logt n/. Creating an empty B-tree To build a B-tree T ,weﬁrstuseB-TREE-CREATE to create an empty root node and then call B-TREE-INSERT to add new keys. Both of these procedures use an auxiliary procedure ALLOCATE-NODE, which allocates one disk page to be used as a new node in O.1/ time. We can assume that a node created by ALLOCATE- NODE requires no DISK-READ, since there is as yet no useful information stored on the disk for that node. B-TREE-CREATE.T / 1 x D ALLOCATE-NODE./ 2 x:leaf D TRUE 3 x:n D 0 4DISK-WRITE.x/ 5 T:root D x B-TREE-CREATE requires O.1/ disk operations and O.1/ CPU time.18.2 Basic operations on B-trees 493 Inserting a key into a B-tree Inserting a key into a B-tree is signiﬁcantly more complicated than inserting a key into a binary search tree. As with binary search trees, we search for the leaf position at which to insert the new key. With a B-tree, however, we cannot simply create a new leaf node and insert it, as the resulting tree would fail to be a valid B-tree. Instead, we insert the new key into an existing leaf node. Since we cannot insert a key into a leaf node that is full, we introduce an operation that splits a full node y (having 2t 1 keys) around its median key y:keyt into two nodes having only t 1 keys each. The median key moves up into y’s parent to identify the dividing point between the two new trees. But if y’s parent is also full, we must split it before we can insert the new key, and thus we could end up splitting full nodes all the way up the tree. As with a binary search tree, we can insert a key into a B-tree in a single pass down the tree from the root to a leaf. To do so, we do not wait to ﬁnd out whether we will actually need to split a full node in order to do the insertion. Instead, as we travel down the tree searching for the position where the new key belongs, we split each full node we come to along the way (including the leaf itself). Thus whenever we want to split a full node y, we are assured that its parent is not full. Splitting a node in a B-tree The procedure B-TREE-SPLIT-CHILD takes as input a nonfull internal node x (as- sumedtobeinmainmemory)andanindexi such that x:ci (also assumed to be in main memory) is a full child of x. The procedure then splits this child in two and adjusts x so that it has an additional child. To split a full root, we will ﬁrst make the root a child of a new empty root node, so that we can use B-TREE-SPLIT-CHILD. The tree thus grows in height by one; splitting is the only means by which the tree grows. Figure 18.5 illustrates this process. We split the full node y D x:ci about its median key S, which moves up into y’s parent node x. Those keys in y that are greater than the median key move into a new node ´, which becomes a new child of x.494 Chapter 18 B-Trees RSTQPUV NW…… RQP TUV NWS…… xx T1T1 T2T2 T3T3 T4T4 T5T5 T6T6 T7T7 T8T8 y D x:ciy D x:ci ´ D x:ciC1 x: key i1 x: key i1 x: key i x: key i x: key iC 1 Figure 18.5 Splitting a node with t D 4. Node y D x:ci splits into two nodes, y and ´,andthe median key S of y moves up into y’s parent. B-TREE-SPLIT-CHILD.x; i/ 1 ´ D ALLOCATE-NODE./ 2 y D x:ci 3 ´:leaf D y:leaf 4 ´:n D t 1 5 for j D 1 to t 1 6 ´:keyj D y:keyjCt 7 if not y:leaf 8 for j D 1 to t 9 ´:cj D y:cj Ct 10 y:n D t 1 11 for j D x:n C 1 downto i C 1 12 x:cjC1 D x:cj 13 x:ciC1 D ´ 14 for j D x:n downto i 15 x:keyjC1 D x:keyj 16 x:keyi D y:keyt 17 x:n D x:n C 1 18 DISK-WRITE.y/ 19 DISK-WRITE.´/ 20 DISK-WRITE.x/ B-TREE-SPLIT-CHILD works by straightforward “cutting and pasting.” Here, x is the node being split, and y is x’s ith child (set in line 2). Node y originally has 2t children (2t 1 keys) but is reduced to t children (t 1 keys) by this operation. Node ´ takes the t largest children (t 1 keys) from y,and´ becomes a new child18.2 Basic operations on B-trees 495 of x, positioned just after y in x’s table of children. The median key of y moves up to become the key in x that separates y and ´. Lines 1–9 create node ´ and give it the largest t 1 keys and corresponding t children of y. Line 10 adjusts the key count for y. Finally, lines 11–17 insert ´ as a child of x, move the median key from y up to x in order to separate y from ´, and adjust x’s key count. Lines 18–20 write out all modiﬁed disk pages. The CPU time used by B-TREE-SPLIT-CHILD is ‚.t/, due to the loops on lines 5–6 and 8–9. (The other loops run for O.t/ iterations.) The procedure performs O.1/ disk operations. Inserting a key into a B-tree in a single pass down the tree We insert a key k into a B-tree T of height h in a single pass down the tree, re- quiring O.h/ disk accesses. The CPU time required is O.th/ D O.t logt n/.The B-TREE-INSERT procedure uses B-TREE-SPLIT-CHILD to guarantee that the re- cursion never descends to a full node. B-TREE-INSERT.T; k/ 1 r D T:root 2 if r:n == 2t 1 3 s D ALLOCATE-NODE./ 4 T:root D s 5 s:leaf D FALSE 6 s:n D 0 7 s:c1 D r 8B-TREE-SPLIT-CHILD.s; 1/ 9B-TREE-INSERT-NONFULL.s; k/ 10 else B-TREE-INSERT-NONFULL.r; k/ Lines 3–9 handle the case in which the root node r is full: the root splits and a new node s (having two children) becomes the root. Splitting the root is the only way to increase the height of a B-tree. Figure 18.6 illustrates this case. Unlike a binary search tree, a B-tree increases in height at the top instead of at the bottom. The procedure ﬁnishes by calling B-TREE-INSERT-NONFULL to insert key k into the tree rooted at the nonfull root node. B-TREE-INSERT-NONFULL recurses as necessary down the tree, at all times guaranteeing that the node to which it recurses is not full by calling B-TREE-SPLIT-CHILD as necessary. The auxiliary recursive procedure B-TREE-INSERT-NONFULL inserts key k into node x, which is assumed to be nonfull when the procedure is called. The operation of B-TREE-INSERT and the recursive operation of B-TREE-INSERT-NONFULL guarantee that this assumption is true.496 Chapter 18 B-Trees T8T7T6T5T4T3T2T1T8T7T6T5T4T3T2T1 FHLDANP FDA LNP s H rr T:root T:root Figure 18.6 Splitting the root with t D 4. Root node r splits in two, and a new root node s is created. The new root contains the median key of r and has the two halves of r as children. The B-tree grows in height by one when the root is split. B-TREE-INSERT-NONFULL.x; k/ 1 i D x:n 2 if x:leaf 3 while i 1 and kx:keyi 16 i D i C 1 17 B-TREE-INSERT-NONFULL.x:ci ;k/ The B-TREE-INSERT-NONFULL procedure works as follows. Lines 3–8 handle the case in which x is a leaf node by inserting key k into x.Ifx is not a leaf node, then we must insert k into the appropriate leaf node in the subtree rooted at internal node x. In this case, lines 9–11 determine the child of x to which the recursion descends. Line 13 detects whether the recursion would descend to a full child, in which case line 14 uses B-TREE-SPLIT-CHILD to split that child into two nonfull children, and lines 15–16 determine which of the two children is now the18.2 Basic operations on B-trees 497 correct one to descend to. (Note that there is no need for a DISK-READ.x:ci/ after line 16 increments i, since the recursion will descend in this case to a child that was just created by B-TREE-SPLIT-CHILD.) The net effect of lines 13–16 is thus to guarantee that the procedure never recurses to a full node. Line 17 then recurses to insert k into the appropriate subtree. Figure 18.7 illustrates the various cases of inserting into a B-tree. For a B-tree of height h,B-TREE-INSERT performs O.h/ disk accesses, since only O.1/ DISK-READ and DISK-WRITE operations occur between calls to B-TREE-INSERT-NONFULL. The total CPU time used is O.th/ D O.t logt n/. Since B-TREE-INSERT-NONFULL is tail-recursive, we can alternatively imple- ment it as a while loop, thereby demonstrating that the number of pages that need to be in main memory at any time is O.1/. Exercises 18.2-1 Show the results of inserting the keys F;S;Q;K;C;L;H;T;V;W;M;R;N;P;A;B;X;Y;D;Z;E in order into an empty B-tree with minimum degree 2. Draw only the conﬁgura- tions of the tree just before some node must split, and also draw the ﬁnal conﬁgu- ration. 18.2-2 Explain under what circumstances, if any, redundant DISK-READ or DISK-WRITE operations occur during the course of executing a call to B-TREE-INSERT.(A redundant DISK-READ is a DISK-READ for a page that is already in memory. A redundant DISK-WRITE writes to disk a page of information that is identical to what is already stored there.) 18.2-3 Explain how to ﬁnd the minimum key stored in a B-tree and how to ﬁnd the prede- cessor of a given key stored in a B-tree. 18.2-4 ? Suppose that we insert the keys f1;2;:::;ng into an empty B-tree with minimum degree 2. How many nodes does the ﬁnal B-tree have? 18.2-5 Since leaf nodes require no pointers to children, they could conceivably use a dif- ferent (larger) t value than internal nodes for the same disk page size. Show how to modify the procedures for creating and inserting into a B-tree to handle this variation.498 Chapter 18 B-Trees JK NO RSTDECAUVYZ PXMG(a) JK NO RSTDEBAUVYZ PXMG(b) C JK NODEBAUVYZ PXMG(c) C RSQ T JK NODEBAUVYZ MG (d) C RSQL P XT JK NODEBAUVYZ MG (e) C RSQL P XT F Q inserted L inserted F inserted initial tree B inserted Figure 18.7 Inserting keys into a B-tree. The minimum degree t for this B-tree is 3, so a node can hold at most 5 keys. Nodes that are modiﬁed by the insertion process are lightly shaded. (a) The initial tree for this example. (b) The result of inserting B into the initial tree; this is a simple insertion into a leaf node. (c) The result of inserting Q into the previous tree. The node RST U V splits into two nodes containing RS and UV,thekeyT moves up to the root, and Q is inserted in the leftmost of the two halves (the RS node). (d) The result of inserting L into the previous tree. The root splits right away, since it is full, and the B-tree grows in height by one. Then L is inserted into the leaf containing JK. (e) The result of inserting F into the previous tree. The node ABCDE splits before F is inserted into the rightmost of the two halves (the DE node).18.3 Deleting a key from a B-tree 499 18.2-6 Suppose that we were to implement B-TREE-SEARCH to use binary search rather than linear search within each node. Show that this change makes the CPU time required O.lg n/, independently of how t might be chosen as a function of n. 18.2-7 Suppose that disk hardware allows us to choose the size of a disk page arbitrarily, but that the time it takes to read the disk page is aCbt,wherea and b are speciﬁed constants and t is the minimum degree for a B-tree using pages of the selected size. Describe how to choose t so as to minimize (approximately) the B-tree search time. Suggest an optimal value of t for the case in which a D 5 milliseconds and b D 10 microseconds. 18.3 Deleting a key from a B-tree Deletion from a B-tree is analogous to insertion but a little more complicated, be- cause we can delete a key from any node—not just a leaf—and when we delete a key from an internal node, we will have to rearrange the node’s children. As in insertion, we must guard against deletion producing a tree whose structure violates the B-tree properties. Just as we had to ensure that a node didn’t get too big due to insertion, we must ensure that a node doesn’t get too small during deletion (except that the root is allowed to have fewer than the minimum number t 1 of keys). Just as a simple insertion algorithm might have to back up if a node on the path to where the key was to be inserted was full, a simple approach to deletion might have to back up if a node (other than the root) along the path to where the key is to be deleted has the minimum number of keys. The procedure B-TREE-DELETE deletes the key k from the subtree rooted at x. We design this procedure to guarantee that whenever it calls itself recursively on a node x, the number of keys in x is at least the minimum degree t. Note that this condition requires one more key than the minimum required by the usual B-tree conditions, so that sometimes a key may have to be moved into a child node before recursion descends to that child. This strengthened condition allows us to delete a key from the tree in one downward pass without having to “back up” (with one ex- ception, which we’ll explain). You should interpret the following speciﬁcation for deletion from a B-tree with the understanding that if the root node x ever becomes an internal node having no keys (this situation can occur in cases 2c and 3b on pages 501–502), then we delete x,andx’s only child x:c1 becomes the new root of the tree, decreasing the height of the tree by one and preserving the property that the root of the tree contains at least one key (unless the tree is empty).500 Chapter 18 B-Trees JK NODEBAUVYZ MG (a) C RSQL P XT F initial tree JK NODEBAUVYZ MG (b) C RSQL P XT F deleted: case 1 JK NODEBAUVYZ G (c) C RSQ L P XT M deleted: case 2a JK NODEBAUVYZ (d) C RSQ L P XT G deleted: case 2c Figure 18.8 Deleting keys from a B-tree. The minimum degree for this B-tree is t D 3, so a node (other than the root) cannot have fewer than 2 keys. Nodes that are modiﬁed are lightly shaded. (a) The B-tree of Figure 18.7(e). (b) Deletion of F . This is case 1: simple deletion from a leaf. (c) Deletion of M. This is case 2a: the predecessor L of M moves up to take M’s position. (d) Dele- tion of G. This is case 2c: we push G down to make node DEGJK and then delete G from this leaf (case 1). We sketch how deletion works instead of presenting the pseudocode. Figure 18.8 illustrates the various cases of deleting keys from a B-tree. 1. If the key k is in node x and x is a leaf, delete the key k from x. 2. If the key k is in node x and x is an internal node, do the following:18.3 Deleting a key from a B-tree 501 JK NOEBAUVYZ (e) C RSQ L PXT D deleted: case 3b JK NOEBAUVYZ C RSQ LP XT JK NOAUVYZC RSQ LP XT(f) B deleted: case 3a E (e′) tree shrinks in height Figure 18.8, continued (e) Deletion of D. This is case 3b: the recursion cannot descend to node CL because it has only 2 keys, so we push P down and merge it with CL and TX to form CLPTX; then we delete D from a leaf (case 1). (e0) After (e), we delete the root and the tree shrinks in height by one. (f) Deletion of B. This is case 3a: C moves to ﬁll B’s position and E moves to ﬁll C’s position. a. If the child y that precedes k in node x has at least t keys, then ﬁnd the predecessor k0 of k in the subtree rooted at y. Recursively delete k0,and replace k by k0 in x. (We can ﬁnd k0 and delete it in a single downward pass.) b. If y has fewer than t keys, then, symmetrically, examine the child ´ that follows k in node x.If´ has at least t keys, then ﬁnd the successor k0 of k in the subtree rooted at ´. Recursively delete k0, and replace k by k0 in x.(We can ﬁnd k0 and delete it in a single downward pass.) c. Otherwise, if both y and ´ have only t 1 keys, merge k and all of ´ into y, so that x loses both k and the pointer to ´,andy now contains 2t 1 keys. Then free ´ and recursively delete k from y. 3. If the key k is not present in internal node x, determine the root x:ci of the appropriate subtree that must contain k,ifk is in the tree at all. If x:ci has only t 1 keys, execute step 3a or 3b as necessary to guarantee that we descend to a node containing at least t keys. Then ﬁnish by recursing on the appropriate child of x.502 Chapter 18 B-Trees a. If x:ci has only t 1 keys but has an immediate sibling with at least t keys, give x:ci an extra key by moving a key from x down into x:ci ,movinga key from x:ci ’s immediate left or right sibling up into x, and moving the appropriate child pointer from the sibling into x:ci. b. If x:ci and both of x:ci ’s immediate siblings have t 1 keys, merge x:ci with one sibling, which involves moving a key from x down into the new merged node to become the median key for that node. Since most of the keys in a B-tree are in the leaves, we may expect that in practice, deletion operations are most often used to delete keys from leaves. The B-TREE-DELETE procedure then acts in one downward pass through the tree, without having to back up. When deleting a key in an internal node, however, the procedure makes a downward pass through the tree but may have to return to the node from which the key was deleted to replace the key with its predecessor or successor (cases 2a and 2b). Although this procedure seems complicated, it involves only O.h/ disk oper- ations for a B-tree of height h, since only O.1/ calls to DISK-READ and DISK- WRITE are made between recursive invocations of the procedure. The CPU time required is O.th/ D O.t logt n/. Exercises 18.3-1 Show the results of deleting C, P ,andV , in order, from the tree of Figure 18.8(f). 18.3-2 Write pseudocode for B-TREE-DELETE. Problems 18-1 Stacks on secondary storage Consider implementing a stack in a computer that has a relatively small amount of fast primary memory and a relatively large amount of slower disk storage. The operations PUSH and POP work on single-word values. The stack we wish to support can grow to be much larger than can ﬁt in memory, and thus most of it must be stored on disk. A simple, but inefﬁcient, stack implementation keeps the entire stack on disk. We maintain in memory a stack pointer, which is the disk address of the top element on the stack. If the pointer has value p, the top element is the .p mod m/th word on page bp=mc of the disk, where m is the number of words per page.Problems for Chapter 18 503 To implement the PUSH operation, we increment the stack pointer, read the ap- propriate page into memory from disk, copy the element to be pushed to the ap- propriate word on the page, and write the page back to disk. A POP operation is similar. We decrement the stack pointer, read in the appropriate page from disk, and return the top of the stack. We need not write back the page, since it was not modiﬁed. Because disk operations are relatively expensive, we count two costs for any implementation: the total number of disk accesses and the total CPU time. Any disk access to a page of m words incurs charges of one disk access and ‚.m/ CPU time. a. Asymptotically, what is the worst-case number of disk accesses for n stack operations using this simple implementation? What is the CPU time for n stack operations? (Express your answer in terms of m and n for this and subsequent parts.) Now consider a stack implementation in which we keep one page of the stack in memory. (We also maintain a small amount of memory to keep track of which page is currently in memory.) We can perform a stack operation only if the relevant disk page resides in memory. If necessary, we can write the page currently in memory to the disk and read in the new page from the disk to memory. If the relevant disk page is already in memory, then no disk accesses are required. b. What is the worst-case number of disk accesses required for n PUSH opera- tions? What is the CPU time? c. What is the worst-case number of disk accesses required for n stack operations? What is the CPU time? Suppose that we now implement the stack by keeping two pages in memory (in addition to a small number of words for bookkeeping). d. Describe how to manage the stack pages so that the amortized number of disk accesses for any stack operation is O.1=m/ and the amortized CPU time for any stack operation is O.1/. 18-2 Joining and splitting 2-3-4 trees The join operation takes two dynamic sets S 0 and S 00 andanelementx such that for any x0 2 S 0 and x00 2 S 00,wehavex0:key y:key 10 exchange x with y 11 FIB-HEAP-LINK.H;y;x/ 12 AŒd D NIL 13 d D d C 1 14 AŒd D x 15 H:min D NIL 16 for i D 0 to D.H:n/ 17 if AŒi ¤ NIL 18 if H:min == NIL 19 create a root list for H containing just AŒi 20 H:min D AŒi 21 else insert AŒi into H’s root list 22 if AŒi:key