This preview shows pages 1–4. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 1 Lecture 10: Lecture 10: Recursion Recursion Analysis & Analysis & Binary Search Binary Search PIC 10B PIC 10B Todd Wittman Todd Wittman Recursion Analysis Recursion Analysis Analyzing the running time T of a recursive algorithm is generally harder than analyzing a nonrecursive one. The most common strategy is to write the run time as a function of N: T(N). This indicates the time needed to process N items. By tracing carefully through the recursion, we can write down a recurrence relation for the algorithm. For example, T(N) = T(N1) + 1 Then we repeat the recurrence T(N) = [T(N2)+1] +1 = T(N2) + 2 T(N) = [T(N3)+1] + 2 = T(N3) + 3 Look for a pattern: T(N) = T(Nk) + k By tracing the pattern all the way to the base case T(1), we can determine the running time of the algorithm. T(N) = O(N) 2 Analyzing the Factorial Analyzing the Factorial Last class, we computed the factorial recursively. int factorial (int N) { if (N==0) return 1; return N*factorial(N1); } Checking the if statement and multiplying by N is O(1) operation. Time for factorial(N) = Time for factorial(N1) + O(1) Dropping the Big O for the moment, we get the recurrence: T(N) = T(N1) + 1 Analyzing the Factorial Analyzing the Factorial Repeatedly plug in the recurrence. T(N) = T(N1) + 1 = T(N2) + 1 + 1 = T(N2) + 2 = T(N3) + 1 + 2 = T(N3) + 3 So the pattern is: T(N) = T(Nk) + k Let k = N. T(N) = T(0) + N T(0) is the time to compute the base case factorial(0), which is just O(1). T(N) = 1 + N = O(N) The nonrecursive version also runs in O(N) time. 3 Analyzing the Palindrome Analyzing the Palindrome Last class we saw the algorithm for checking for palindromes like "racecar"....
View
Full
Document
This note was uploaded on 04/27/2010 for the course PIC 15705120 taught by Professor Wittman during the Winter '10 term at UCLA.
 Winter '10
 Wittman

Click to edit the document details