17 Pages

Handout 10

Course: CS 103B, Winter 2008
School: Stanford
Rating:
 
 
 
 
 

Word Count: 5525

Document Preview

Sahami Mehran CS103B Handout #10 January 23, 2009 Analysis of Algorithms: The Recursive Case We again thank Maggie Johnson for portions of this handout. Up until now, we have been analyzing non-recursive algorithms, looking at how big-Oh notation may be used to characterize the growth rate of running times for various algorithms. Such algorithm analysis becomes a bit more complicated when we turn our attention...

Register Now

Unformatted Document Excerpt

Coursehero >> California >> Stanford >> CS 103B

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Sahami Mehran CS103B Handout #10 January 23, 2009 Analysis of Algorithms: The Recursive Case We again thank Maggie Johnson for portions of this handout. Up until now, we have been analyzing non-recursive algorithms, looking at how big-Oh notation may be used to characterize the growth rate of running times for various algorithms. Such algorithm analysis becomes a bit more complicated when we turn our attention to analyzing recursive algorithms. As a result, we augment the analytic tools in our repertoire to help us perform such analyses. One such tool is an understanding of recurrence relations, which we discuss presently. Recurrence Relations Recall that a recursive or inductive definition has the following parts: 1. Base Case: the initial condition or basis which defines the first (or first few) elements of the sequence 2. Inductive (Recursive) Case: an inductive step in which later terms in the sequence are defined in terms of earlier terms. The inductive step in a recursive definition can be expressed as a recurrence relation, noting how earlier terms in a sequence relate to late terms. We more formally define this notion below. A recurrence relation for a sequence a1, a2, a3, ... is a formula that relates each term ak to certain of its predecessors ak-1, ak-2, ..., ak-i, where i is a fixed integer and k is any integer greater than or equal to i. The initial conditions for such a recurrence relation specify the values of a1, a2, a3, ..., ai-1. A recursive definition is one way of defining a sequence in mathematics (other ways to define sequences include enumerating the sequence or coming up with a formula to express the sequence). Suppose you have an enumerated sequence that satisfies a given recursive definition (or recurrence relation). It is frequently very useful to have the formula for the elements of this sequence in addition to the recurrence relation, especially if you need to determine a very large member of the sequence. Such an explicit formula is called a solution to the recurrence relation. If a member of the sequence can be calculated using a fixed number of elementary operations, we say it is a closed form formula. Solving recurrence relations is the key to analyzing recursive subprograms. Example 1 A single pair of rabbits (one male and one female, of course) is born at the end of January 200 9. Assume the following interesting conditions: 1. Rabbit pairs give birth to one new male/female pair at the end of every month after the month in which they are born. 2. No deaths ever occur (not even from exhaustion...) 2 Problem: Find a recurrence relation that can be used to tell us how many rabbits we will have at the end of one year (i.e., the end of January 2010). Solution: We will keep track of time by using the variable x to denote the number of months that have passed since January 2009, and the function Tx to denote how many rabbits are currently in the population as a function of x. Thus, the end of January 2009 is denoted by x = 0. Since we know we have two rabbits at the end of January 2009, we can write: T0 = 2. Note that this function determines the base case in our recursive definition. Now, we need to determine how many rabbits there are in the population as a function of the number of rabbits that were in the population in the previous month. Since every month, each male/female pair produces a new male/female pair, the number of rabbits in the population at the end of a month is equal to the number of rabbits that were already alive, plus one new rabbit pair for each rabbit pair that was previously alive. More formally, we can write this as a recurrence relation: Tx = Tx-1 + Tx-1 Given this recurrence relation, and the value of the base case, T0, we can compute the number of rabbits in the population after the passage of any number of months. In Death, as in Life Bring on the Recurrence Relation Many problems in the biological, management, and social sciences lead to sequences that satisfy recurrence relations. Here are the famous Lancaster Equations of Combat: Two armies engage in combat. Each army counts the number of soldiers still in combat at the end of the day. Let a0 and b0 denote the number of soldiers in the first and second armies, respectively, before combat begins, and let an and bn denote the number of men in the two armies at the end of the nth day. Thus, an-1 - an represents the number of soldiers lost by the first army on the nth day. Similarly, bn-1 - bn represents the number of soldiers lost by the second army on the nth day. Suppose it is known that the decrease in the number of soldiers in each army is proportional to the number of soldiers in the other army at the beginning of each day. Thus, we have constants A and B such that an-1 - an = A * bn-1 and bn-1 - bn = B * an-1. These constants measure the effectiveness of the weapons of the different armies, and can be computed using the recurrence relations for a and b. Solving Recurrence Relations Using Repeated Substitution One method of solving recurrence relations is called repeated substitution. It works like magic. No, seriously, it works like this: you take the recurrence relation and use it to enumerate elements of the sequence back from k. To find the next element back from k, we substitute k-1 in for k in the recurrence relation. 3 Example 2 Consider the following recurrence relation: a0 = 1 ak = ak-1 + 2 Problem: What is the closed form formula for this recurrence relation? We start by substituting k-1 into the recursive definition above to obtain: ak-1 = ak-2 + 2 Then, we substitute this value for ak-1 back in the original recurrence relation equation. We do this because we want to find an equation for ak, so if we enumerate back from k, but substitute those equations in the formula for ak, we will hopefully find a pattern. What we are looking for is a lot of different representations of the formula for ak based on previous elements in the sequence. So, ak = ak-1 + 2 = (ak-2 + 2) + 2 = ak-2 + 4 Then, we substitute k-2 for k in the original equation to get ak-2 = ak-3 + 2 and then substitute this value for ak-2 in the previous expression: ak = ak-2 + 4 = (ak-3 + 2) + 4 = ak-3 + 6 ak = ak-3 + 6 = (ak-4 + 2) + 6 = ak-4 + 8 ak = ak-4 + 8.... The pattern that emerges is obvious: ak = ak-i + 2i. We need to get rid of some of these variables though. Specifically, we need to get rid of the ak-i on the right-hand side of the equation to get a closed form formula. In other words, we do not have to evaluate previous members of the sequence to get the one we want. So, we set i = k, yielding: ak = a0 + 2k ak = 1 + 2k To substantiate this substitution (setting i = k), we would have to do a proof by induction to show that the recurrence relation represents the same sequence as the closed form formula. Since, theres no better time than the present, we present this proof here presently. Proof (by induction): Let P(n) denote the following: if a1, a2, a3, ..., an is the sequence defined by: 1. a0 = 1 2. ak = ak-1 + 2 then, an = 1 + 2n for all n >= 1 Base Case: prove that P(1) is true. Using the definition of the recurrence relation, we have: a1 = a0 + 2 = 1 + 2 = 3. Now, we show that we get the same answer using the formula: an = 1 + 2n for n = 1. an = 1 + 2n = 1 + 2 = 3. Therefore, the base case holds. 4 Inductive Case: The induction hypothesis is to assume P(k): ak = 1 + 2k. We then need to show that P(k+1) = ak+1 = 1 + 2(k + 1). ak+1 = a((k+1)1) + 2 ak+1 = ak + 2 ak+1 = 1 + 2k + 2 ak+1 = 1 + 2(k + 1) from the recurrence relation (this is a "given") algebra substitution from inductive hypothesis (ak = 1 + 2k) algebra Thus, we have shown the desired result. Since P(k+1) is true when P(k) is true, and we have shown P(1) holds, we have shown inductively that P(n) is true for all n >= 1. Example 3 Recurrence Relations and Graphs: Two Great Tastes that Taste Great Together Let Kn be a complete graph on n vertices (i.e., between any two of the n vertices lies an edge). Define a recurrence relation for the number of edges in Kn, and then solve this by enumerating and guessing a formula. Solution: By inspection, we can see that K1 = 0, since that graph has no edges. Now, we conjecture that adding another vertex to the graph will require us to add edges from each of the existing vertices in the graph to the new vertex we added. Thus, if there were already n vertices in the graph, when we add the (n + 1)st vertex, we must add n new edges to the graph to make it a complete graph. This gives us the recurrence relation: Kn+1 = Kn + n or, alternatively Kn = Kn-1 + (n 1) Enumerating the first few values of this sequences yields: K2 = K1 + 1 = 0 + 1 = 1 K3 = K2 + 2 = 1 + 2 = 3 K4 = K3 + 3 = 3 + 3 = 6 K5 = K4 + 4 = 6 + 4 = 10 These numbers seem to match the graphs given. So far, so good. Now, we just need to generalize a formula from this sequence. From the recurrence relation, we can see that this sequence may be given by the formula (for all n >= 1): n-1 Kn 0 + 1 + 2 + ... + (n 1) = i=0 i = n(n 1)/2 5 We dont give a full inductive proof here that this formula is, in fact, correct, but the curious reader can quickly prove this themselves to get a little more comfortable with using induction. Example 4 Consider the Tower of Hanoi puzzle (which you probably saw already in CS106B/X), which is defined by three pegs and a series of disks of various sizes that may be placed on the pegs. The disks all start by being placed in ascending order by size on the first peg. This configuration is depicted below. The object of the Towers of Hanoi is to move all the disks from the first peg to the third peg while always following the following rules: 1. Only one disk may be moved at a time (specifically, the top disk on any peg). 2. At no time can a larger disk be placed on a smaller one. Thus, the goal configuration of the puzzle is: The pseudocode for a recursive algorithm that can solve this problem is given below, where k is the number of disks to move, Beg is the peg to move the disks from, Aux is the peg that may be used an "auxiliary storage" during the move, and End is the peg that the disks must ultimately be moved to. Tower(k, Beg, Aux, End) { if (k == 1) move disk from Beg to End; else { Tower(k-1, Beg, End, Aux); move disk from Beg to End; Tower(k-1, Aux, Beg, End); } } 6 Let Hn denote the number of moves to solve the Tower of Hanoi puzzle with n disks. Moving the n 1 disks from the beginning peg to the auxiliary peg requires Hn-1 moves. Then, use one move to transfer the bottom disk from the beginning peg to the ending peg. Finally, the n 1 disks on the auxiliary peg are moved to the ending peg, requiring an additional Hn-1 moves. This give us the recurrence relation: Hn = 2Hn-1 + 1 The base case for this relations is H0 = 0, since if there are no disks, there are no moves required to have all the disks on the third peg. To determine a closed form formula where there is no Hn on the right side of the equation, we will try repeated substitution: Hn = 2Hn-1 + 1 = 2(2Hn-2 + 1) + 1 = 22 * Hn-2 + 2 + 1 = 22 (2Hn-3 + 1) + 2 + 1 = 23 * Hn-3 + 22 + 2 + 1 The pattern to this recurrence relation is: Hn = (2i * Hn-i) + 2i-1 + 2i-2 + ... + 22 + 21 + 20 We can set n = i (this will require an inductive proof): Hn = (2n * H0) + 2n-1 + 2n-2 + ... + 22 + 21 + 1 Substituting H0 = 0, yields the formula: Hn = 2n-1 + 2n-2 + ... + 22 + 21 + 1 This is a well known summation formula that can easily be proven by induction to be equal to 2n 1. Therefore, the number of moves required for n disks is 2n 1. There is an ancient myth of this puzzle that says there is a tower in Hanoi where monks are transferring 64 gold disks from one peg to another according to the rules of the puzzle. They take one second to move one disk. The myth says that the world will end when they finish the puzzle. A quick calculation to see how much time this will take reveals: 264 1 = 1,446,744,073,709,551,615 seconds So, the monks should be busy for about 500 billion years to solve the puzzle. Lucky for us. Not so lucky for the monks who probably arent having much fun moving disks from peg to peg. Example 5 (From Rosen) Problem: Find a recurrence relation and give initial conditions for the number of bit strings (strings of 0s and 1s) of length n that do not have two consecutive 0s. Solution: Let an denote the number of bits strings of length n that do not have two consecutive 0s. To obtain a recurrence relation for an, note that the number of bit strings of length n that do not contain two consecutive 0s equals the number of such bit strings 7 ending with 0 plus the number of such bit strings ending with a 1. We assume n >= 3, so that the bit string has at least three bits. The bit strings of length n ending in 1 that do not contain two consecutive 0s are precisely the bit strings of length n 1 without two consecutives 0s with a 1 added at the end. Consequently, there are an-1 such strings. Bit strings of length n ending with a 0 that do not have two consecutive 0s must have 1 as their (n 1)st bit; otherwise they would end with a pair of 0s since the nth bit is a 0. It follows that the bit strings of length n ending with 0 that do not have two consecutive 0s are precisely the bit strings of length n 2 without two consecutive 0s with 10 added at the end. Consequently, there are an-2 such bit strings. Putting this all together, we conclude that an = an-1 + an-2 for n >= 3. The initial conditions are a1 = 2, since both strings of length 1, namely the strings 0 and 1, do not contain two consecutive 0s. Similarly, a2 = 3, since 01, 10, and 11 do not contain two consecutive 0s. Example 6 Find a closed form solution for the following recurrence relations. For brevity, we omit the inductive proofs. a) Recurrence relation: a0 = 2 an = 3an-1 Solution: an = 3an-1 2 an = 3 (3an-2) = 3 an-2 2 3 an = 3 (3an-3) = 3 an-3 an = 3 i -1 (3an-i) = 3 an-i i Set i = n, yielding: n an = 3 a0 n an = 2 * 3 8 b) Recurrence relation: a0 = 1 an = 2an-1 1 Solution: 2 an = 2(2an-2 1) 1 = 2 an-2 2 1 2 3 2 an = 2 (2an-3 1) 2 1 = 2 an-3 2 2 1 an = 2 (an-i) 2 i i -1 2 i -2 2 0 Set i = n, yielding: n n -1 n -2 0 n n -1 n -2 0 an = 2 (a0) 2 2 2 = 2 2 2 2 n n an = 2 (2 1) an = 1 Note that while the recurrence relation looks deceptively similar to the recurrence relation in the Tower of Hanoi problem, the solution to the recurrence relation here gives a vastly different result. c) Recurrence relation: a0 = 5 an = nan-1 Solution: an = n(n-1)an-2 an = n(n-1)(n-2)an-3 an = n(n-1)(n-2)(n-i+1)an-i Set i = n, yielding: an = n(n-1)(n-2)(1) a0 = a0 n! an = 5n! Analyzing Recursive Programs Solving recurrence relations is the key to analyzing recursive programs. We need a formula that represents the number of recursive calls and the work done in each call as the program converges to the base case. We will then use this formula to determine an upper bound on the program's worst-case performance. In terms of the analysis of algorithms, a recurrence relation has can be viewed as follows: A recurrence relation expresses the running time of a recursive algorithm. This includes how many recursive calls are generated at each level of the recursion, how much of the problem is solved by each recursive call, and how much work is done at each level. 9 Say we have some unknown running time for function F that is defined in terms of F's parameter n (since this parameter controls the number of recursive calls). We call this TF(n). The value of TF(n) is established by an inductive definition based on the size of argument n. There are two cases, examined below: 1. n is sufficiently small that no recursive calls are made. This case corresponds to a base case in an inductive definition of TF(n). 2. n is sufficiently large that recursive calls made. are However, we assume that whatever recursive calls F makes, they will be made with smaller parameter values. This case corresponds to an inductive step in the definition of TF(n). The recurrence relation for TF(n) is derived by examining the code of F and defining the running times for the two cases stated above. We then solve the recurrence relation to derive a big-Oh expression for F. Example 7 Consider the following function to compute factorials: int factorial(int n) { if (n <= 1) return(1); else return(n * factorial(n-1)); } 1) 2) 3) We will use T(n) to represent the unknown running time of this function with n as the size of the parameter. For the base case of the inductive definition of T(n), we will take n to equal 1, since no recursive calls are made in this case. When n = 1, we execute only lines 1 and 2, each of which has a constant running time (i.e., O(1)) which we will just designate as some time value a. When n > 1, the condition of line 1 is false so we execute lines 1 and 3. Line 1 takes some constant time value b and line 3 takes T(n-1) since we are making a recursive call. If the running time of factorial with parameter value n is T(n), then the running time for a call to factorial with parameter value n 1 will be T(n-1). This gives the following recurrence relation: base case: T(1) = a induction: T(n) = b + T(n-1), for n > 1 10 Now we must solve this recurrence relation to come up with a closed form formula. We can try just enumerating a few to see if there is a pattern: T(1) = a T(2) = b + T(1) = b + a T(3) = b + T(2) = b + (b + a) = a + 2b T(4) = b + T(3) = b + (a + 2b) = a + 3b T(n) = a + (n-1)b for all n >= 1 To be complete, we need to do an inductive proof to show that the running time formula T(n) = a + (n-1)b is true for all n >= 1. Proof: Let P(n) denote that the running time of factorial is T(n) = a + (n-1)b. And, recall that the recurrence relation definition give us: T(1) = a, and T(n) = b + T(n-1) for n > 1. Base case: prove that P(1) is true T(1) = a + ((1 1) * b) = a + (0 * b) = a. This equation holds since the base case of our inductive definition states that T(1) = a. Inductive case: inductive hypothesis is to assume P(k): T(k) = a + (k-1)b, and show P(k+1): T(k+1) = a + kb. We know from the recurrence relation definition that T(k+1) = b + T(k). We use the inductive hypothesis to substitute for T(k). This gives us: T(k+1) = b + T(k) = b + a + (k-1)b = b + a + kb - b = a + kb P(k+1) holds when P(k) holds, and P(1) holds, therefore P(n) is true for all n >= 1. Now that we know the closed form formula for this recurrence relation, we use this formula to determine the complexity. T(n) = a + (n-1)b = a + bn - b has a complexity of O(n). This makes sense: all it says is that to compute n!, we make n calls to factorial, each of which requires O(1) time. 11 Example 8 Consider the following recursive selection sort algorithm: void SelectionSort(int A[], int i, int n) { 1) 2) 3) 4) 5) 6) 7) 8) 9) } if (i < n) { int small = i; for (int j = i + 1, j <= n, j++) { if (A[j] < A[small]) small = j; } int temp = A[small]; A[small] = A[i]; A[i] = temp; SelectionSort(A, i + 1, n); } Parameter n indicates the size of the array, parameter i tells us how much of the array is left to sort, specifically A[i...n]. So, a call to SelectionSort(A,1,n) will sort the entire array through recursive calls. We now develop a recurrence relation. Note that the size of the array to be sorted on each recursive call is equal to n i + 1. We will denote this value as m, the size of the array during any particular recursive call. There is one base case (m = 1). In this case, only line 1 is executed, taking some constant amount of time which we will call a. Note that m = 0 is not the base case because the recursion converges down to a list with one element; when i = n, m = 1. The inductive case is for m > 1: this is when recursive calls are made. Lines 2, 6, 7, and 8 each take a constant amount of time. The for loop of lines 3, 4 and 5 will execute m times (where m = n i + 1). So a recursive call to this function will be dominated by the time it takes to execute the for loop m times, which we shall designate O(m). The time for the recursive call of line 9 is T(m-1). So, the inductive definition of recursive SelectionSort is: T(1) = a T(m) = T(m-1) + O(m) To solve this recurrence relation, we first get rid of the big-Oh expression by substituting the definition of big-Oh: (f(n) = O(g(n)) if f(n) <= C * g(n)), so we can substitute C*m for O(m): T(1) = a T(m) = T(m-1) + C*m 12 Now, we can either try repeated substitutions or just enumerate a few cases to look for a pattern. Lets try repeated substitution: T(m) = T(m-1) + C*m = T(m-2) + 2Cm - C = T(m-3) + 3Cm - 3C = T(m-4) + 4Cm - 6C = T(m-5) + 5Cm - 10C ... = T(m-j) + jCm - (j(j-1)/2)C because T(m-1) = T(m-2) + C(m-1) because T(m-2) = T(m-3) + C(m-2) because T(m-3) = T(m-4) + C(m-3) because T(m-4) = T(m-5) + C(m-4) To get a closed form formula we let j = m 1. We do this because our base case is T(1). If we were to continue the repeated substitution down to the last possible substitution, we want to stop at T(1) because T(0) is really not the base case that the recursion converges on. (Note that we have to do an inductive proof later to allow us to do this substitution, but for now): T(m) = T(1) + (m-1)Cm - ((m-1)(m-2)/2)C = a + m2C - Cm - (m2C - 3Cm + 2C)/2 = a + (2m2C - 2Cm - m2C + 3Cm - 2C)/2 = a + (m2C + Cm - 2C)/2 So, finally we have a closed form formula T(m) = a + (m2C + Cm - 2C)/2. The complexity of this formula is O(m2), which is the same complexity as iterative selection sort, so doing it recursively did not save us any time. The above recurrence relation generally occurs with any recursive subprogram that has a single loop of some form, and then does a recursive call (usually where there is tail recursion involved). Example 9 MergeSort is an efficient sorting algorithm that uses a "divide and conquer" strategy. That is, the problem of sorting a list is reduced to the problem of sorting two smaller lists, and then merging those smaller sorted lists. Suppose that we have a sorted array A with r elements and another sorted array B with s elements. Merging is an operation that combines the elements of A with the elements of B into one large sorted array C that has (r + s) elements. MergeSort is based on this merging algorithm. What happens is we set up a recursive function that divides a list into two halves. We then sort the two halves and merge them together. The question is how do you sort the two halves? We sort them by using MergeSort recursively. The pseudocode for MergeSort is given below: MergeSort(L) 1) if (length of L > 1) { 2) Split list into first half and second half 3) MergeSort(first half) 4) MergeSort(second half) 5) Merge first half and second half into sorted list } 13 Note: we will also assume that we have Split and Merge functions that each run in O(n). The recursive calls continue dividing the list into halves until each half contains only one element; obviously a list of one element is sorted. The algorithm then merges these smaller halves into larger sorted halves until we have one large sorted list. For example, if the list contains the following integers: 7 9 2 4 3 6 1 8 The first thing that happens is we split the list into 2 halves (well refer to this call as MergeSort #0 = original call): 7 9 4 2 3 6 1 8 Then we call Mergesort recursively on the first half which again splits the list into two halves: (MergeSort #1): 7 9 4 2 We call Mergesort recursively again on the first half, which splits the list into two parts again: (MergeSort #2) 7 9 When we call MergeSort the next time, the if condition is false and we return up a level of recursion to MergeSort #2. Now we execute the next line in MergeSort #2: MergeSort(second half) which executes on the list containing just 9. Again the if condition is false, and we return back up to MergeSort #2. We execute the next line, which merges the sorted lists containing 7 and 9, producing: 7 9 We have completed MergeSort #2. Now we return up to recursive call MergeSort #1 and find we are on the list containing 4 and 2. We execute the next line in MergeSort #1, calling MergeSort(second half) on the list containing 4 and 2, and end up with separate lists of 4 and 2: 4 2 We end up merging these two sorted lists into one list containing 2 and 4 just as we did with the 7 and 9, producing: 2 4 Once that work is complete, we return to MergeSort #1 and execute the merge on the two lists each with two elements. This produces the sorted list: 2 4 7 9 14 We return to recursive call MergeSort #0 (the original call) and execute the next line: MergeSort(second half). This sends us through another cycle of recursion just like what we did for the first part of the list. When we finish, we have a second sorted list: 1 3 6 8 The last line of MergeSort #0 merges these two sorted lists of four elements into one sorted list: 1 2 3 4 6 7 8 9 To analyze the complexity of MergeSort, we need to define a recurrence relation. The base case is when we have a list of 1 element and only line 1 of the function is executed. Thus, the base case is constant time, O(1). If the test of line 1 fails, we must execute lines 2-5. The time spent in this function when the length of the list > 1 is the sum of the following: 1) O(1) for the test on line 1 2) O(n) for the split function call on line 2 3) T(n/2) for recursive call on line 3 4) T(n/2) for recursive call on line 4 5) O(n) for the merge function call on line 5 If we drop the O(1)'s and apply the summation rule, we get 2T(n/2) + O(n). If we substitute constants in place of the big-Oh notation we obtain: T(1) = a T(n) = 2T(n/2) + bn To solve this recurrence relation, we will enumerate a few values. We will stick to n's that are powers of two so things divide evenly: T(2) = 2T(1) + 2b = 2a + 2b T(4) = 2T(2) + 4b = 2(2a + 2b) + 4b = 4a + 8b T(8) = 2T(4) + 8b = 2(4a + 8b) + 8b = 8a + 24b T(16) = 2T(8) + 16b = 2(8a + 24b) + 16b = 16a + 64b There is obviously a pattern but it is not as easy to represent as the others have been. Note the following relationships: value of n: coefficient of b: ratio: 2 2 1 4 8 2 8 24 3 16 64 4 So, it appears that the coefficient of b is n times another factor that grows by 1 each time n doubles. The ratio is log2 n because log2 2 = 1, log2 4 = 2, log2 8 = 3, etc. Our "guess" for the solution of this recurrence relation is T(n) = an + bn log2 n. 15 We could have used repeated substitution in which case we would have the following formula: T(n) = 2i T(n/2i) + ibn Now, if we let i = log2 n, we end up with: n*T(1) + bn log2 n = an + bn log2 n (because 2log2n = n). Of course, we would have to do an inductive proof to show that this formula does indeed hold for all n >= 1, but we leave the proof as an exercise for the reader. Finally, note that the complexity of an + bn log2 n is O(n log n), which is considerably faster than Selection Sort. You will often see this recurrence relation in "divide and conquer" sorts. A Theorem in the Home or Office is a Good Thing Fortunately, there is a handy theorem that is often useful in analyzing the complexity of general divide and conquer algorithms. Theorem 1 (Master Theorem): Let f be an increasing function that satisfies the recurrence relation: f(n) = a f(n/b) + cnd whenever n = bk, where k is a positive integer, a >= 1, b is an integer greater than 1, c is a positive real number, and d is a non-negative real number. Then: f(n) = O(nd) O(nd log n) O(n logb a if a < bd if a = bd if a > bd ) Example 10 Problem: Use Theorem 1 above to find the big-Oh running time of MergeSort (from Example 9). Solution: In Example 9, we are given the recurrence relation for MergeSort as: T(n) = 2T(n/2) + xn where we have simply replaced the positive constant b in the original recurrence relation with the constant x, so that we do not confuse variable names below. In order to apply Theorem 1, we must show that this recurrence relation fits the functional form for f(n) in the theorem. We choose: a = 2, b = 2, c = x, and d = 1. With these constants, the function f(n) in the theorem becomes: f(n) = 2 f(n/2) + xn1 16 Note that f(n) now matches the function T(n) given earlier, making Theorem 1 applicable to the recurrence relation T(n). Given our choice of constants, we know that a = bd, since 2 = 21. Thus, Theorem 1 tell us the complexity of our recurrence relation is O(nd log n). Since we chose d = 1, we obtain the final complexity result O(n log n), which is the same complexity value we obtained via repeated substitution. Example 11 Problem: Use repeated substitution to find the time complexity of the function recurse. Verify your result using induction. /* Assume only non-negative even values of n are passed in */ void recurse(int n) { int total = 0; 1) 2) 3) 4) } if (n == 0) return 1; for (int i = 0; i < 4; i++) { total += recurse(n-2); } return total; Solution: When n = 0 (the base case), this function only executes line 1, doing O(1) work. We will note this constant amount of work as a. When n >= 2 (the recursive case), this function does O(1) work in executing lines 1, 2, and 4, which we will denote by b, and also makes four recursive calls with parameter values n-2 in the body loop (line 3). We use these two points to perform the recurrence relation analysis below. From the base case, we have: From the recursive case, we have: T0 = a Tn = 4Tn-2 + b We apply repeated substitution: Tn = 4Tn-2 + b 2 Tn = 4(4Tn-4 + b) + b = 4 Tn-4 + 4b + b 2 3 2 Tn = 4 (4Tn-6 + b) + 4b + b = 4 Tn-6 + 4 b + 4b + b Tn = 4 Tn-2i + 4 k 2k i i- 1 b+4 i -2 b++4 b 0 Note that 4 = 2 , yielding: 2i 2(i-1) 2(i-2) 0 Tn = 2 Tn-2i + 2 b+2 b++2 b Set i = n/2, yielding: n n -2 n -4 0 n n -2 n -4 0 Tn = 2 T0 + 2 b + 2 b + + 2 b = 2 a + (2 + 2 + + 2 ) b 17 So, we need to compute the closed form for (2 n -2 +2 n -4 + + 2 ) = (2 1)/3. 0 n Here is a brief digression on how we compute this closed form formula: n -2 n -4 0 Let x = (2 + 2 + + 2 ) 2 2 n -2 n -4 0 n n -2 2 So, 2 x = 4x = 2 (2 + 2 + + 2 ) = (2 + 2 + + 2 ) 2 x x = 3x = (2 + 2 n 0 n 3x = 2 2 = 2 1 x = (2 1)/3 = (2 n n -2 2 n n -2 + + 2 ) (2 0 2 n -2 +2 n -4 ++2 ) 0 +2 n -4 ++2 ) Substituting this closed form for the sum back in to the equation for Tn yields: n n -2 n -4 0 Tn = 2 a + (2 + 2 + + 2 ) b n n Tn = 2 a + ((2 1)/3) b Now, we verify this result using induction. Let P(n) denote Tn = 2 a + ((2 1)/3) b. Base case: Show P(0). 0 0 T0 = 2 a + ((2 1)/3) b = a + ((1 1)/3) b = a. This is the initial condition. Inductive case: Assume inductive hypothesis P(n): Tn = 2 a + ((2 1)/3) b Show P(n+2): Tn+2 = 2 n+2 n n n n a + ((2 n+2 1)/3) b Note: only consider even values of n Tn+2 = 4Tn + b n n Tn+2 = 4(2 a + ((2 1)/3) b) + b 2n n Tn+2 = 2 (2 a + ((2 1)/3) b) + b n+2 n+2 2 Tn+2 = 2 a + ((2 2 )/3) b + b n+2 n+2 Tn+2 = 2 a + ((2 3 1)/3) b + b n+2 n+2 Tn+2 = 2 a + ((2 1)/3) b b + b n+2 n+2 Tn+2 = 2 a + ((2 1)/3) b QED. by definition of the recurrence substituting Tn with the inductive hypothesis 2 algebra: 4 = 2 2 algebra: multiply in the 2 2 algebra: -2 = -3 - 1 algebra: (-3/3)b = -b this is the desired result Finally, we calculate the big-Oh complexity for the function, as follows: n n From the recurrence relation Tn = 2 a + ((2 1)/3) b, we see that the algorithm has time n n n n n complexity: O(2 a) + O(2 b) = O(2 ) + O(2 ) = O(2 ). Bibliography A. Aho, J. D. Ullman, Foundations of Computer Science, New York: W.H. Freeman, 1992. T. Cormen, C. Leiserson, R. Rivest, Introduction to Algorithms, New York: McGraw-Hill, 1991. K. Rosen, Discrete Mathematics and its Applications (6th Ed.), New York: McGraw-Hill, 2007.
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Stanford - CS - 103B
Mehran Sahami CS103BHandout #11 January 23, 2009Analyzing Searching and SortingIn examining methods to analyze both recursive and non-recursive algorithms, it is only fitting to spend a little time looking at a variety of common algorithms and their co
Stanford - CS - 103B
Mehran Sahami CS103BHandout #12 January 23, 2009Problem Set #2 Due: 11:00am on Monday, February 2nd1. Let R be a relation on the set cfw_1, 2, 3, 4, 5 containing the ordered pairs: cfw_&lt;1,1&gt;,&lt;1,2&gt;,&lt;1,3&gt;,&lt;2,3&gt;,&lt;2,4&gt;,&lt;3,1&gt;,&lt;3,4&gt;,&lt;3,5&gt;,&lt;4,2&gt;,&lt;4,5&gt;,&lt;5,1&gt;,&lt;
Stanford - CS - 103B
Mehran Sahami CS103BHandout #13 January 28, 2009Managing a Bestiary of Algorithms: Complexity Classes and NP-CompletenessThanks to Maggie Johnson for some portions of this handout.A Quick Introduction to NP-CompletenessImagine that you have decided t
Stanford - CS - 103B
Mehran Sahami CS103BHandout #16 February 2, 2009Problem Set #3 Due: 11:00am on Wednesday, February 11thNote: in the problems below in which you are asked for a big-Oh running time, we are looking for a tight big-Oh bound (analogous to the big-Theta ()
Stanford - CS - 103B
Mehran Sahami CS103BHandout #17 February 2, 2009Introduction to TreesHierarchical StructuresTrees are very useful conceptual tools for representing relationships among certain classes of items. For example, trees can be used to represent familial rela
Stanford - CS - 103B
Mehran Sahami CS103BHandout #19 February 6, 2009Practice Midterm ProblemsNote: the number of problems here is a larger than you will see on the actual midterm. More problems are provided here just to give you a bit more practice on a broader set of the
Stanford - CS - 103B
Mehran Sahami CS103BHandout #20 February 6, 2009Practice Midterm Problem Solutions(including some hints and shortcuts you might find useful for exams) 1. Order in which nodes are processed if we were to do a reverse preorder traversal on the tree: a, c
Stanford - CS - 106B
CS106B Winter 2009Handout 01CS106B Course InformationJerry Cainjerry@cs.stanford.eduJanuary 7th, 2009Instructor: E-Mail: Office phone: Office: Office hours: Lectures:725-8597 Gates 192 Wednesdays, 10:00 a.m. noon MWF 9:00 9:50 a.m. Gates Building,
Stanford - CS - 106B
CS106B Winter 2009Handout 02Early Programming: Landmarks and LandminesJanuary 7th, 2009Handout written by Julie Zelenski, Mehran Sahami, and Robert Plummer.After todays lecture, you should run home read all of Chapter 1 on your own. We won't teach th
Stanford - CS - 106B
CS106B Winter 2009Handout 03Two-Dimensional Grids and Queen SafetyJanuary 9, 2008This handout was written by Jerry.Today's larger example demonstrates the use of a grid of Boolean valuesthat is, a single declaration of a Grid&lt;bool&gt;to maintain informa
Stanford - CS - 106B
CS106B Winter 2009Handout 04C+ StringsJanuary 12, 2009Original handout written by Neal Kanodia, with help from Steve Jacobson.C+ Strings One of the most useful data types supplied in the C+ libraries is the string. A string is a variable that stores
Stanford - CS - 106B
CS106B Winter 2009Handout 05Crash Course: Records and FilesJanuary 12, 2009Your task is to design a data structure to keep track of the academic departments on campus. There are an unbounded numbers of departments, and each department has a name and a
Stanford - CS - 106B
CS106B Winter 2009Handout 06Assignment 1: Blocky!January 12, 2009Brand- new assignment!Your first assignment has you implement variation on a one-player game called Blocky. The rules are simple: click any single block and drag the mouse to outline a
Stanford - CS - 106B
CS106B Winter 2009Handout 07Good Programming StyleJanuary 14, 2009Thanks to Julie Zelenski, Nick Parlante, and Bob Plummer for this handout.As we will stress all quarter, a working program is only half the challengeconstructing an elegant and well-en
Stanford - CS - 106B
CS106B Winter 2009Handout 08DecompositionJanuary 14th, 2009Due to Nick Parlante.Decomposition is the process of breaking a large problem into more manageable subproblems. The motivating principle is that large problems are disproportionately harder t
Stanford - CS - 106B
CS106B Winter 2009Handout 09Coding StandardsJanuary 14th, 2009Handout written by Nick Parlante. Quite possibly the funniest handout ever.Landmarks in Coding Quality Let's honestly review the conceptual landmarks most programmers use when thinking abo
Stanford - CS - 106B
CS106B Winter 2009Handout 10C+ and CS106 Library ReferenceJanuary 14, 2009Written by Julie Zelenski.You're sitting at your computer, trying to write some code that manipulates a string or stream or draws some graphics. You know the functionality you
Stanford - CS - 106B
CS106B Winter 2009Handout 11Section Handout 1January 14, 2009Problem 1: Compiler, compiler, what do you want? You are working hard on your latest assignment and come up with the following code:enum directionT cfw_ North, East, South, West ; int main(
Stanford - CS - 106B
CS106B Winter 2009Handout 11SSection Solution 1January 14 - 16, 2009Problem 1: Compiler, compiler, what do you want? The line that will not compile in this example is the line that performs the assignment dir = num;. Why not? Enumerated types are repr
Stanford - CS - 106B
CS106B Winter 2009Handout 12MDebugging with XCodeJanuary 16, 2009Many thanks to Justin2, Jason, and Julie for portions of this handout.Using the Xcode debugger Note: this handout refers to Xcode 2.5. The windows for Xcode 3.1 will look slightly diffe
Stanford - CS - 106B
CS106B Winter 2008Handout 13CS106 Library ClassesJanuary 16, 2008Kudos to Julie Zelenski for this fantastic summary of the CS106 utility and container classes.This summer Im going to try something that another lecturer successfully tried last quarter
Stanford - CS - 106B
CS106B Winter 2009Handout 14Electronic SubmissionJanuary 17, 2009This handout was written by Mehran Sahami and updated by Nick Miyake and Jerry Cain.Submission procedures When you submit a completed assignment, you will turn it two versions, a paper
Stanford - CS - 106B
CS106B Winter 2009Handout 15Section Handout 2January 21, 2009Problem 1: Using the Scanner and Stack classes&lt;html&gt;&lt;b&gt;&lt;i&gt;CS106 rules!&lt;/i&gt;&lt;/b&gt;&lt;/html&gt;Web browsers use stacks to track html tags such as &lt;b&gt;, &lt;i&gt; or &lt;html&gt;. Every html tag must be matched b
Stanford - CS - 106B
CS106B Winter 2009Handout 15SSection Solution 2January 21 22, 2009Problem 1: Using the Scanner and Stack classes#include &quot;stack.h&quot; #include &quot;scanner.h&quot; bool ProcessOpenTag(Scanner&amp; scanner, Stack&lt;string&gt;&amp; tagStack) cfw_ string tag = scanner.nextToken
Stanford - CS - 106B
CS106B Winter 2009Handout 17CS106 Library Classes: Take IIJanuary 21, 2009Kudos to Julie Zelenski for this fantastic summary of the CS106 utility and container classes.More on Map Last handout, we noted that the map assumes that keys are of string ty
Stanford - CS - 106B
CS106B Winter 2009Handout 18Introduction to RecursionJanuary 28, 2009Today we'll start working with one of CS106Bs neatest ideas: recursion. Recursion often does the trick whenever the problem to be solved can be broken down into virtually identical (
Stanford - CS - 106B
CS106B Winter 2009Handout 19Section Handout 3January 28, 2009Problem 1: Presidential Speech Tag Cloud Youre handed a Vector&lt;Map&lt;int&gt; &gt; of length 209. The kth item in this Vector is a Map&lt;int&gt; which stores the number of times a nontrivial word appeared
Stanford - CS - 106B
CS106B Winter 2009Handout 19SSection Solution 3January 28 - 30, 2009Solution 1: US Presidential Speech Tag Cloud You may have seen of the web site that inspired this problem. If not, check outhttp:/chir.ag/phernalia/preztags/.This problem was intend
Stanford - CS - 106B
CS106B Winter 2009Handout 20Assignment 3: Recursion Problem SetJanuary 30, 2009This week your task is structured as a problem set, consisting of several small problems to solve in isolation. Recursion is a difficult concept to master and one that is w
Stanford - CS - 106B
CS106B Winter 2009Handout 21Section Handout 4February 4, 2009Problem 1: Towers Of Hanoi Revisited One of the first procedural recursion problems we discussed in lecture was the classic Towers Of Hanoi problem. The recursive solution lists a series of
Stanford - CS - 106B
CS106B Winter 2009Handout 23CS106B Practice MidtermFebruary 6th, 2009Exam Facts: When: Wednesday, February 11th at 7:00 p.m. Where: TBD (probably Dinkelspiel Auditorium, but still waiting for confirmation) Coverage The midterm will test everything up
Stanford - CS - 106B
CS106B Autumn 2009Handout 23SCS106B Practice SolutionFebruary 6th, 2009Solution 1: Acronymsvoid ReadIntoMap(ifstream&amp; in, Map&lt;Vector&lt;string&gt; &gt;&amp; map) cfw_ Scanner s; s.setSpaceOption(Scanner:IgnoreSpaces); while (true) cfw_ string line; getline(in, li
Stanford - CS - 106B
CS106B Winter 2009Handout 29Section Handout 6February 18, 2009Problem 1: Removing Duplicates Write a function RemoveDuplicates that given a linked list will remove and free the second of all neighboring duplicates found in the list. If the incoming li
Stanford - CS - 106B
CS106B Winter 2009Handout 29SSection Solution 6February 18-20, 2009Problem 1: Removing Duplicatesvoid RemoveDuplicates(node *list) cfw_ for (node *cur = list; cur != NULL; cur = if (cur-&gt;next != NULL &amp; cur-&gt;value = node *duplicate = cur-&gt;next; cur-&gt;n
Old Dominion - ENGLISH - 12
www.GetPedia.com*More than 150,000 articles in the search database *Learn how almost everything worksEnglish Vocabulary in UseCAMBRIDGEU NIVERSITY PRESSPUBLISHED BY T H E PRESS SYNDICATE O F T H E UNIVERSITY OF CAMBRIDGET he Pitt Building, Trumpingt
Old Dominion - ENGLISH - 15
New New Headway Intermediate Testsea e a ho TeachHea tocopi lass o p da ar omfe un l, stndt a s ho iada o p da ar somfe un l, stndt a C mater tte.tion i riadati is a e c mate tte. on Casstaught an e co short staught anduexplained thoroughly, Cas rse zer
Golden West - BIOL 200 - BIOL 200
Summer 2009 Bio 200Pharmacology: An Introduction to Basic Drug GroupsCourse Objective Students will study the classication of medications and basic principles of pharmacology from legislation and pharmacokinetics through receptor theory, pharmacodynamic
Golden West - BIOL 200 - BIOL 200
DrugsofthePeripheralNervousSystemNervousSystems2DivisionsCentralBrain SpinalCordPeripheralVoluntary Involuntary AutonomicSympathetic ParasympatheticEffectorCellsofthe PeripheralNervousSystemVoluntarySkeletalMuscleAutonomicCardiacMuscle SmoothMu
Golden West - BIOL 200 - BIOL 200
Unit 10Serums, Vaccines &amp; HormonesTypes of ImmunityNatural (Inborn) ActiveMake Own AntibodiesAcquiredPassiveGiven Preformed AntibodiesExposureInjection Vaccine ToxoidMother to FetusSerums(Gamma Globulins)Diabetes Mellitus Characterized by el
Golden West - BIOL 200 - BIOL 200
Unit 9DiureticsFiltrationReabsorption Secretion ExcretionDCT: Aldosterone PCT: 100% Nutrients Reabsorbed`Clor HCO3-K+ o r H +Powerful Reabsorption: Cl- &amp; Na+Collecting Tubule: Loop of Henle:Counter Current Mechanism Sets up ability to concentrat
Golden West - BIOL 200 - BIOL 200
Unit 8Eye, Skin &amp; AntimicrobialsWide Angle1Narrow AngleThree major types of glaucoma and basic treatment: Congenital Glaucoma surgery required Primary Glaucoma Narrow angle (also called acute congestive) cause: poor drainage because of position of
Golden West - BIOL 200 - BIOL 200
Unit 7Respiratory, Antihistaminic &amp; GI DrugsAsthma: Bronchoconstriction Increased mucus productionManaging the Airway Drugs to open the airway Drugs to treat the inflammation Decrease the airway remodeling Remodeling describes the permanent, negativ
Golden West - BIOL 200 - BIOL 200
Drugs of the Central Nerous SystemStimulation Increases: Convulsions or Seizures Sensory Acuity Motor Activity Tremors &amp; Hallucinations Anxiety Euphoria Normal -Neutral Sedation (Drowsy) Hypnosis (Sleep) General Anesthesia Coma DeathDeathDepression Inh
Golden West - BIOL 200 - BIOL 200
Unit 5Drugs of the Cardiovascular SystemCardiotonic drugs Drugs that increase the strength of the heart. Drugs for a failing heart.The heart becomes weaker as a pump. Can happen over many years or rapidly in response to injury Goals for treatment: in
Golden West - BIOL 200 - BIOL 200
Lecture 2How effective is the drug at producing a pharmacologic response. How well does it relief symptoms Not concerned with how much a person needs totake to get the effectMaximum effect of the drugThe amount of the drug necessary to produce a phar
Golden West - BIOL 200 - BIOL 200
Welcome to Pharmacolgy Biology 200Petitioners will be added at the end of lectureDr. Kate EganOffice: HS 115 Phone: 714.892.7711 ext. 51125 Hours: Tuesday 2:15-3:15 / 5:30-6:30 PM Wednesday 6:00 - 7:00 PM or by appointment Email: cegan@gwc.cccd.edu Cou
Golden West - BIOL 200 - BIOL 200
PHARMACOLOGY: Homework AssignmentDue: Worth: Time:PRINT NAME:_ Three ID#:_Last Class Meeting Before Final Exam - Will not be accepted late. 5 points Do not spend more than 30 minutesUSE: DRUG FACTS AND COMPARISONS1. Use the Table of Contents of Drug
Golden West - BIOL 200 - BIOL 200
PRINT NAME: _ ID#:_ PHARMACOLOGY: HOMEWORK 2 Due: Meeting When Beginning Unit 7 - Will not be accepted late. Worth: 5 points Time: Do not spend more than 30 minutesUSE: DRUG FACTS AND COMPARISONS1. Use the Table of Contents from the front of Drug Facts
Golden West - BIOL 200 - BIOL 200
Print Name:_ Student ID #:_ Pharmacology: Homework Assignment One Due: March 4, 2009 5 pts Look up a drug of your choice in 3 a Physicians Desk Reference Book, a Drug Facts &amp; Comparisons Book and another drug reference book of your choice. Goal of the ass
Golden West - BIOL 200 - BIOL 200
Pharmacology Final Study OutlineUnit 1-3 (8) Understand Ionization and how it pertains to the movement of a drug Know the difference between potency and efficacy Review Drug Schedule/ prescription writing procedures How are drugs namedtrade names, generi
Golden West - BIOL 200 - BIOL 200
Name:_ ID #:_ Bio 200- Pharmacology Additional Extra Credit Assignment Due 5/20 NO LATE ASSIGNMENTS WILL BE ACCEPTED Write on this sheet of paper (you can use both sides if needed) Research the mechanism of action of the diuretics furosemide (Lasix) and s
Golden West - BIOL 200 - BIOL 200
Pharmacology Extra Credit AssignmentWorth 5 points Due Meeting Before Final Exam Accepted Earlier but not laterAssignment:1. Read one article in a professional journal which has been published within the past 15 months. This includes major science maga
Golden West - BIOL 200 - BIOL 200
Pharmacology Exam 3 Review (Units 6-8) Unit 6 Drugs of the CNS Memorize the Continum Chart Understand the 2 types of tolerance Factors contributing to drug dependence CNS Stimulants how do they work? What are the main types we talked about in class the ma
Golden West - BIOL 200 - BIOL 200
EXAM 2 REVIEW Unit 4 Drugs of the Peripheral Nervous System What are preganglionic and postganglionic neurons and where are they found? How many efferent neurons in the SNS, PNS, voluntary portion of the nervous system What are the main receptors we talke
Golden West - BIOL 200 - BIOL 200
Outline of Central Nervous System DrugsDirections: MEMORIZE THIS A. CNS Stimulants - increase activity of ALL parts of the CNS 1. Amphetamines and related compounds 2. Xanthines (including caffeine, theobromine, and theophylline) 3. Cocaine and related l
Monmouth IL - CAAM - 236
EE236A (Fall 2007-08)Lecture 13 Convergence analysis of the barrier method complexity analysis of the barrier method convergence analysis of Newtons method choice of update parameter bound on the total number of Newton iterations initialization131Comp
Monmouth IL - CAAM - 236
EE236A (Fall 2007-08)Lecture 14 Primal-dual interior-point methods primal-dual path-following Mehrotras corrector step computing the search directions141Central path and complementary slacknesss + Ax b = 0 AT z + c = 0 zisi = 1/t, z 0, i = 1, . . . ,
Monmouth IL - CAAM - 236
EE236A (Fall 2007-08)Lecture 15 Self-dual formulations initialization and infeasibility detection skew-symmetric LPs homogeneous self-dual formulation self-dual formulation151Solution of an LPgiven a pair of primal and dual LPs minimize cT x subject
Monmouth IL - CAAM - 236
EE236A (Fall 2007-08)Lecture 16 Large-scale linear programming cutting-plane method Benders decomposition delayed column generation Dantzig-Wolfe decomposition161Cutting-plane methodminimize cT x subject to Ax b A Rmn, m n general idea: solve sequenc
Monmouth IL - CAAM - 236
EE236A (Fall 2007-08)Lecture 17 Integer linear programming integer linear programming, 0-1 linear programming a few basic facts branch-and-bound171Denitioninteger linear program (ILP) minimize cT x subject to Ax b, x ZncGx = dmixed integer linear
Monmouth IL - CAAM - 236
EE236A (Fall 2007-08)Lecture 1 Introduction and overview linear programming example from optimal control example from combinatorial optimization history course topics software11Linear program (LP)nminimizej =1 ncj xj aij xj bi,j =1 nsubject toi