Recursion B.Ramamurthy 2/23/2019 Ramamurthy
Introduction Recursion is one of most powerful methods of solution available to computer scientists. We will study application of recursion for solving simple problems. Later on we will reexamine recursion in the context of tree ADT. 2/23/2019 Ramamurthy
Recursive Solutions Recursion is an important problem solving approach that is an alternative to iteration. These are questions to answer when using recursive solution: 1. How can you define the problem in terms of a smaller problem of the same type? 2. How does each recursive call diminish the size of the problem? 3. What instance of the problem can serve as the base case? 4. As the problem size diminishes, will you reach this base case? 2/23/2019 Ramamurthy
Recursion Methodology Initial Case Stopping case Continue case Computation that progresses towards result and stopping case 2/23/2019 Ramamurthy
Example 1: Factorial of N Iterative definition: Factorial(N) = N * (N-1) * (N-2) *…1 for any N > 0. Factorial(0) = 1 Recursive solution: 1. Factorial(N) = N * Factorial(N-1) 2. Problem diminishing? yes. 3. Base case/stopping case: Factorial(0) = 1; base case does not have a recursive call. 4. Can reach base case as problem diminishes? yes 2/23/2019 Ramamurthy
Java Methods for Factorial int factorialIterative(int N) { tmp = 1; while (N > 1) { tmp = tmp * N; N = N –1; } return tmp; } int factorial (int N) if (n == 0) return 1; // base case return (N * factorial(N-1)); } 2/23/2019 Ramamurthy
ArrayList ArrayList ArrayList(); //constructor boolean add(Object o); Object remove(int index); int indexOf(Object o); boolean isEmpty(); int size(); Object[] toArray(); // it also has a list iterator that it inherits from AbstractList // this helps in traversal thru’ the list public ListIterator listIterator() 2/23/2019 Ramamurthy
ListIterator An iterator for lists that allows the programmer to traverse the list in either direction, and modify the list during iteration. ListIterator boolean hasNext(); Object next(); Usage: See ArrayTest.java discussed earlier 2/23/2019 Ramamurthy