Recursion Lakshmish Ramaswamy Factorial Computation How is Recursion

  • Slides: 8
Download presentation
Recursion Lakshmish Ramaswamy

Recursion Lakshmish Ramaswamy

Factorial Computation

Factorial Computation

How is Recursion Supported • Method invocation requires bookkeeping – Recursion is no different

How is Recursion Supported • Method invocation requires bookkeeping – Recursion is no different (may be a special case) • Activation records for implementing methods – Activation records hold important information like parameter values & local variables

Stacks for Activation Records • Stack is a good data structure for reversing order

Stacks for Activation Records • Stack is a good data structure for reversing order – First-In-Last-Out paradigm • Why stacks? – Notice that methods return in reverse order of invocation • Activation record at top is that of currently active method – When a method is called, its activation record is pushed on the stack – Top record is popped when the method returns

Stacks and Recursive Methods • Each method invocation results in an activation record •

Stacks and Recursive Methods • Each method invocation results in an activation record • The base case is the last one to be pushed in and the first one to pop out

Fibonacci Numbers • Definition – FN = FN-1 + FN-2 – F 1 =

Fibonacci Numbers • Definition – FN = FN-1 + FN-2 – F 1 = 1 – F 0 = 0 • Very interesting properties – Sum of first N Fibonacci numbers < FN+2 – Sum of squares of two consecutive Fibonacci numbers is also a Fibonacci number • Natural recursive implementation

Simple but Inefficient Implementation

Simple but Inefficient Implementation

What is the Problem? • Each call to fib(n-1) and fib(n-2) results in calling

What is the Problem? • Each call to fib(n-1) and fib(n-2) results in calling fib(n-3) • Keeps getting worse – Observe how many times F 2, F 1 and F 0 are called • Lesson – Avoid duplicate work of solving same instance in separate duplicate calls