{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lec10

# Lec10 - Lecture 10 Lecture Recursion Analysis Binary Search...

This preview shows pages 1–4. Sign up to view the full content.

1 Lecture 10: Lecture 10: Recursion Recursion Analysis & Binary Search Binary Search PIC 10B PIC 10B Todd Todd Wittman Wittman Recursion Analysis Recursion Analysis Analyzing the running time T of a recursive algorithm is generally harder than analyzing a non-recursive 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(N-1) + 1 Then we repeat the recurrence T(N) = [T(N-2)+1] +1 = T(N-2) + 2 T(N) = [T(N-3)+1] + 2 = T(N-3) + 3 Look for a pattern: T(N) = T(N-k) + 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)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
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(N-1); } Checking the if statement and multiplying by N is O(1) operation. Time for factorial(N) = Time for factorial(N-1) + O(1) Dropping the Big O for the moment, we get the recurrence: T(N) = T(N-1) + 1 Analyzing the Factorial Analyzing the Factorial Repeatedly plug in the recurrence. T(N) = T(N-1) + 1 = T(N-2) + 1 + 1 = T(N-2) + 2 = T(N-3) + 1 + 2 = T(N-3) + 3 So the pattern is: T(N) = T(N-k) + 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 non-recursive 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".

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 9

Lec10 - Lecture 10 Lecture Recursion Analysis Binary Search...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online