Recursion B Ramamurthy 262022 Ramamurthy 1 Introduction Recursion
Recursion B. Ramamurthy 2/6/2022 Ramamurthy 1
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/6/2022 Ramamurthy 2
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/6/2022 Ramamurthy 3
Recursion Methodology Initial Case Stopping case Continue case Computation that progresses towards result and stopping case 2/6/2022 Ramamurthy 4
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/6/2022 Ramamurthy 5
Java Methods for Factorial int factorial. Iterative(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/6/2022 Ramamurthy 6
Array. List(); //constructor boolean add(Object o); Object remove(int index); int index. Of(Object o); boolean is. Empty(); int size(); Object[] to. Array(); // it also has a list iterator that it inherits from Abstract. List // this helps in traversal thru’ the list public List. Iterator list. Iterator() 2/6/2022 Ramamurthy 7
List. Iterator An iterator for lists that allows the programmer to traverse the list in either direction, and modify the list during iteration. List. Iterator boolean has. Next(); Object next(); Usage: See Array. Test. java discussed earlier 2/6/2022 Ramamurthy 8
- Slides: 8