COP 3804 INTERMEDIATE JAVA Recursion Recursion The term

  • Slides: 7
Download presentation
COP 3804 - INTERMEDIATE JAVA Recursion

COP 3804 - INTERMEDIATE JAVA Recursion

Recursion • The term “recursion” refers to the fact that the same computation recurs,

Recursion • The term “recursion” refers to the fact that the same computation recurs, or occurs repeatedly, as a problem is solved. • A problem can be solved with recursion if it can be broken down into successive smaller problems that are identical to the overall problem. • Usually, problems that can be solved with recursion can also be solved with a loop. In fact, the recursive algorithm might even be less efficient. But sometimes, the recursive solution is simpler to implement than the iterative solution.

Recursive vs. Iterative Algorithms • What makes an iterative algorithm more efficient that the

Recursive vs. Iterative Algorithms • What makes an iterative algorithm more efficient that the recursive counterpart? Each time a method is called, the following actions are performed by the JVM: • A new instance of each method parameter is created in memory and is initialized to the argument’s value. • Memory also needs to be allocated for local variables. • The memory address of the program location where control returns after the method returns needs to be stored. Note: The steps above are called overhead, which is not needed for loops.

Recursion works like this: • A base case is established. • If matched, the

Recursion works like this: • A base case is established. • If matched, the method solves it and returns. • If the base cannot be solved now: • the method reduces it to a smaller problem (recursive case) and calls itself to solve the smaller problem. By reducing the problem with each recursive call, the base case will eventually be reached and the recursion will stop.

Checklist for Programming with Recursion 1. Make sure that each base case returns the

Checklist for Programming with Recursion 1. Make sure that each base case returns the correct answer. 2. Make sure that each non-base case returns the correct answer, assuming that each of its recursive calls returns the correct answer. 3. Make sure that each recursive call is on a smaller input.

Recursion • In the recursive case, you must always reduce the problem to a

Recursion • In the recursive case, you must always reduce the problem to a smaller version of the original problem, so that progress is made towards the base case. • The base case must eventually be reached for the recursion to stop.

References • Horstmann, Cay. Big Java 4 th ed. New York, USA: John Wiley

References • Horstmann, Cay. Big Java 4 th ed. New York, USA: John Wiley & Sons, Inc. , 2010. • Gaddis, Tony, and Godfrey Muganda. Starting out with Java : From Control Structures through Data Structures. 2 nd ed. Boston: Pearson Addison Wesley, 2007. Print. • G. Smith (personal communication, September 5, 2013)