Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Chapter 10.

Similar presentations


Presentation on theme: "Recursion Chapter 10."— Presentation transcript:

1 Recursion Chapter 10

2 What Is Recursion? It is a problem-solving process
Breaks a problem into identical but smaller problems Eventually you reach a smallest problem Answer is obvious or trivial Using that solution enables you to solve the previous problems Eventually the original problem is solved

3 What Is Recursion? A method that calls itself is a recursive method
The invocation is a Recursive call Recursive invocation /** Task: Counts down from a given positive integer. integer an integer > 0 */ public static void countDown(int integer) { System.out.println(integer); if (integer > 1) countDown(integer - 1); } // end countDown

4 When Designing Recursive Solution
What part of the solution can you contribute directly What smaller but identical problem has a solution that … When taken with your contribution provides solution to the original problem When does the process end? What smaller but identical problem has known solution Have you reached the base case

5 When Designing Recursive Solution
Method definition must provide parameter Leads to different cases Typically includes an if or a switch statement One or more of these cases should provide a non recursive solution The base or stopping case One or more cases includes recursive invocation Takes a step towards the base case A recursive routine may contain a loop but do NOT use the loop termination directly as the base case.

6 Recursive Control Recursion: execution of repetitious stages as subtasks of previous (like) stages Activations: copies of a recursive routine during execution Requires initialization, modification, test for termination Terminal condition = base case (degenerative case) Cf. Brookshear, Computer Science: An Introduction

7 Rules for Recursive Routines
Base case where answer is known immediately All other cases must be defined in terms of the function Sequence of recursive calls converges to the base case

8 For computing x! recursively
What is the efficiency? public static int factorial(int n) { if (n<2) return 1; else return n*factorial(n-1); }

9 For computing x! recursively
The efficiency is O(n) public static int factorial(int n) { if (n<2) return 1; else return n*factorial(n-1); }

10 public static int factorial(int n) { if (n < 2) return 1; else
A recursive method f(n) computes n!. Imagine that this method is called from some other method to compute f(5). Show the changing stack contents for this process. To compute f(5), must 1st compute f(4), so push f(5) f(5)=5*f(4) f(4) must 1st compute f(3), so push f(4) f(4)=4*f(3) f(3) must 1st compute f(2), so push f(3) f(3)=3(f(2) f(2) must 1st compute f(1), so push f(2) f(2)=2*f(1) f(1) = 1; pop f(2); replace f(1) with 1 and compute f(2) f(3)=3*f(2) f(2) = 2; pop f(3); replace f(2) with 2 and compute f(3) f(3) = 6; pop f(4); replace f(3) with 6 and compute f(4) f(4) = 24; pop f(5); replace f(4) with 24 and compute f(5); f(5) =120. Thus, f(5)=120 public static int factorial(int n) { if (n < 2) return 1; else return n * factorial(n - 1); }

11 For computing xn recursively
What is the efficiency? public static double power(double x, int n) { double result; if (n==0) result=1; else result=x*power(x,n-1); return result; }

12 For computing xn recursively
Efficiency is O(n) for this simple algorithm The efficiency can be as good as O(log n) public static double power(double x, int n) { double result; if (n==0) result=1; else result=x*power(x,n-1); return result; }

13 This has a natural looking recursive solution
Fibonacci numbers First two numbers of sequence are 1 and 1 Successive numbers are the sum of the previous two 1, 1, 2, 3, 5, 8, 13, … This has a natural looking recursive solution

14 The recursive algorithm
What is the efficiency? Algorithm Fibonacci(n) if (n < 2) return 1 else return Fibonacci(n-2) + Fibonacci(n-1)

15 A recursive method fib(n) computes the nth Fibonacci number
A recursive method fib(n) computes the nth Fibonacci number. Imagine that this method is called from some other method to compute fib(5). Show the changing stack contents for this process. From the definition of the Fibonacci numbers: f(1)=1, f(2)=1, f(n)=f(n-2)+f(n-1) for n>2 To compute f(5), must 1st compute f(3), so push f(5) f(5)=f(3)+f(4) f(3) must 1st compute f(1), so push f(3) f(3)=f(1)+f(2) f(1)=1; pop f(3); replace f(1) with 1 Now must compute f(2), f(3)=1+f(2) f(2)=1; pop f(2) with 1; compute f(3) =1+1=2 Pop f(5); replace f(3) with 2 Must now compute f(4), so push f(5) f(5)=2+f(4) f(4) must 1st so push f(4) f(4)=f(2)+f(3) f(2)=1; pop f(4); replace f(2) with 1 f(5)=2+f(4) Now must compute f(3), so push f(4) f(4)=1+f(3) To compute f(3), must 1st compute f(1), so push f(3) f(3)=f(1)+f(2) f(1)=1; pop f(3); replace f(1) with 1 compute f(2), f(3)=1+f(2) f(2)=1;pop f(2) with 1; compute f(3)=1+1=2 Pop f(4); replace f(3) with 2; compute f(4)=1+2=3 Pop f(5); replace f(4) with 3; compute f(5)=2+3=5 public static int fib(n) { if (n < 2) return 1; else return fib(n - 2) + fib(n - 1); } Thus, f(5)=5

16 A Poor Solution to a Simple Problem
What is the complexity of the recursive solution? What is the complexity of the iterative solution? The computation of the Fibonacci number F6 (a) recursively; (b) iteratively

17 A Poor Solution to a Simple Problem
Time efficiency grows exponentially with n Iterative solution is O(n) The computation of the Fibonacci number F6 (a) recursively; (b) iteratively

18 A Simple Solution to a Difficult Problem
Fig The initial configuration of the Towers of Hanoi for three disks Demo…

19 A Simple Solution to a Difficult Problem
Rules for the Towers of Hanoi game Move one disk at a time. Each disk you move must be a topmost disk. No disk may rest on top of a disk smaller than itself. You can store disks on the second pole temporarily, as long as you observe the previous two rules. Demo…

20 A Simple Solution to a Difficult Problem
Fig The sequence of moves for solving the Towers of Hanoi problem with three disks. Continued → Demo…

21 A Simple Solution to a Difficult Problem
Fig (ctd) The sequence of moves for solving the Towers of Hanoi problem with three disks

22 A Simple Solution to a Difficult Problem
Fig The smaller problems in a recursive solution for four disks

23 A Simple Solution to a Difficult Problem
Algorithm for solution with 1 disk as the base case Algorithm solveTowers(numberOfDisks, startPole, tempPole, endPole) if (numberOfDisks = = 1) Move disk from startPole to endPole else { solveTowers(numberOfDisks-1, startPole, endPole, tempPole) solveTowers(numberOfDisks-1, tempPole, startPole, endPole) }

24 Recursive Depth-First Search
//Algorithm: Depth-First Search // writes nodes in graph “g” in depth-first order from node “a” procedure depthFirst(Graph g; Node a) { begin mark a visited; write (a); for each node n adjacent to a do if n not visited then depthFirst(g,n); end;

25 Recursively Processing an Array
When processing an array recursively, divide it into two pieces Last element one piece, rest of array another or First element one piece, rest of array another Divide array into two halves

26 Recursively Processing an Array
Compare the following methods… Public static void displayArray(int array[ ], int first, last) { System.out.print(array[first] + “ ”); if (first < last) displayArray(array, first+1, last); } if (first <= last) { displayArray(array, first, last-1); System.out.print(array[last] + “ ”);

27 Recursively Processing an Array
Public static void displayArray(int array[ ], int first, last) { if (first == last) System.out.print(array[first] + “ ”); else { int mid = (first + last)/2; displayArray(array, first, mid); displayArray(array, mid+1, last); }

28 Recursively Processing an Array
Fig Two arrays with middle elements within left halves

29 Recursively Processing a Linked Chain
To write a method that processes a chain of linked nodes recursively Use a reference to the chain's first node as the method's parameter Then process the first node Followed by the rest of the chain public void display( ) { displayChain(firstNode); System.out.println(); } // end display private void displayChain(Node currentNode) { if (currentNode != null) { System.out.print(currentNode.data + " "); displayChain(currentNode.next); } } // end displayChain

30 Recursively Processing a Linked Chain
What does displaySpecial() do? public void display( ){ displaySpecial(firstNode); System.out.println(); } // end display private void displaySpecial(Node currentNode){ if (currentNode != null) { displaySpecial(currentNode.next); System.out.print(currentNode.data + " "); } } // end displaySpecial

31 Note A recursive method part of an implementation of an ADT is often private Its necessary parameters make it unsuitable as an ADT operation

32 Tail Recursion Occurs when the last action performed by a recursive method is a recursive call This performs a repetition that can be done more efficiently with iteration Conversion to iterative method is usually straightforward public static void countDown(int integer) { System.out.println(integer); if (integer > 1) countDown(integer - 1); } // end countDown

33 Mutual Recursion Another name for indirect recursion
Happens when Method A calls Method B Which calls Method C Which calls Method A etc. Difficult to understand and trace Happens naturally in certain situations

34 Fig. 10-11 An example of mutual recursion.


Download ppt "Recursion Chapter 10."

Similar presentations


Ads by Google