Download presentation
Presentation is loading. Please wait.
1
CS 211 Object Oriented Programming
Tail Recursion
2
Tail Recursion A method is tail recursive if the last action of the recursive method is the recursive call Recursion puts frame on the stack the additional overhead required by non-tail recursion could be costly for large inputs
3
Non Tail Recursion //Factorial public static int recurciveFact(int n)
{ if(n == 0) return 1; } else return n*recurciveFact(n-1);
4
Simulation recurciveFact(4) = 4*recurciveFact(3)
=1*1 =1 = 2*1 = 2 = 3*2 = 6 = 4*6 = 24
5
Recursion in Stack Factorial :
6
Tail Recursion – Factorial
public static int tailrecurciveFact(int n) { return factorial(n,1); } private static int factorial(int n,int accum) if(n==0) return accum; else{ return factorial(n-1,n*accum);
7
Simulation tailrecurciveFact(4) = factorial(4,1)
factorial(4,1) = factorial(3,4*1) factorial(3,4*1) = factorial(2,4*1*3) factorial(2,4*1*3) = factorial(1,4*1*3*2) factorial(1,4*1*3*2) = factorial(0,4*1*3*2*1) = 24 factorial(2,4*1*3) = 24 factorial(3,4*1) = 24 factorial(4,1) = 24 tailrecurciveFact(4) = 24;
8
Tail Recursion - Fibonacci
public int fibonacci(int n) { if(n == 0) return 0; else if(n == 1) return 1; else return fibonacci(n - 1) + fibonacci(n - 2); }
9
Simulation //Fibonacci fibonacci(5) = fibonacci(4) + fibonacci(3)
10
Non-Tail Recursion public String rev(String w) {
if(w == null || w.equals("")) return w; else return rev(w.substring(1, w.length())) + w.substring(0,1); }
11
Tail Recursion //”hook” public String rev(String w) {
return tailRev(w, ""); } //tail recursion public String tRev(String w, String res) { if(w==null || w.equals("")) return res; else return tRev(w.substring(1, w.length()), w.charAt(0) + res);
12
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.