12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

36 Chap. 2 Mathematical PreliminariesBecause we have merely guessed at a pattern <strong>and</strong> not actually provedthat this is the correct closed form solution, we can use an induction proof<strong>to</strong> complete the process (see Example 2.13).Example 2.9 A slightly more complicated recurrence isT(n) = T(n − 1) + n; T (1) = 1.Exp<strong>and</strong>ing this recurrence a few steps, we getT(n) = T(n − 1) + n= T(n − 2) + (n − 1) + n= T(n − 3) + (n − 2) + (n − 1) + n.We should then observe that this recurrence appears <strong>to</strong> have a pattern thatleads <strong>to</strong>T(n) = T(n − (n − 1)) + (n − (n − 2)) + · · · + (n − 1) + n= 1 + 2 + · · · + (n − 1) + n.This is equivalent <strong>to</strong> the summation ∑ nclosed-form solution.i=1i, for which we already know theTechniques <strong>to</strong> find closed-form solutions for recurrence relations are discussedin Section 14.2. Prior <strong>to</strong> Chapter 14, recurrence relations are used infrequently inthis book, <strong>and</strong> the corresponding closed-form solution <strong>and</strong> an explanation for howit was derived will be supplied at the time of use.2.5 RecursionAn algorithm is recursive if it calls itself <strong>to</strong> do part of its work. For this approach<strong>to</strong> be successful, the “call <strong>to</strong> itself” must be on a smaller problem then the oneoriginally attempted. In general, a recursive algorithm must have two parts: thebase case, which h<strong>and</strong>les a simple input that can be solved without resorting <strong>to</strong>a recursive call, <strong>and</strong> the recursive part which contains one or more recursive calls<strong>to</strong> the algorithm where the parameters are in some sense “closer” <strong>to</strong> the base casethan those of the original call. Here is a recursive Java function <strong>to</strong> compute the

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!