Recursion Concepts Implementation Data Structures and Algorithms in Java, Third EditionCh05 – 1
The factorial function n! =1 ∙ 2 ∙ 3 ∙ … ∙ (n – 1) ∙ n ?? n! = 1 if n = 0 (base case, anchor) n ∙ (n – 1)!if n > 0 (inductive step) Data Structures and Algorithms in Java, Third EditionCh05 – 2
Application of the definition of n! = 3 ∙ 2! = 2 ∙ 1! = 1 ∙ 0! = ? 0! = ? = 1 ∙ 1 = 1 = 2 ∙ 1 = 2 = 3 ∙ 2 = 63! 1! 2! = 1 Data Structures and Algorithms in Java, Third EditionCh05 – 3
Implementation of the factorial function long factorial(long n) { if (n == 0) return 1; else return n * factorial(n-1); } Data Structures and Algorithms in Java, Third EditionCh05 – 4
Stack frame parameters and local variables return value return address Data Structures and Algorithms in Java, Third EditionCh05 – 5
Executing the factorial method long factorial(long n) { if (n == 0) return 1; else return n * factorial(n-1); } void f() { long m = factorial(3); } (20) (10) Data Structures and Algorithms in Java, Third EditionCh05 – 6
0 ? (10) 1 ? 2 ? 3 ? (20) 0 1 (10) 1 ? 2 ? 3 ? (20) 1 1 (10) 2 ? 3 ? (20) 2 2 (10) 3 ? (20) * ? (10) 2 ? 3 ? (20) 2 ? (10) 3 ? (20) 3 ? * * long factorial(long n) { if (n == 0) return 1; else return n * factorial(n-1); } void f() { long m = factorial(3); } (20) (10) Data Structures and Algorithms in Java, Third EditionCh05 – 7
Tracing recursion void f(int n) { if (n > 0) { f(n-1); System.out.print(n + " "); f(n-1); } Data Structures and Algorithms in Java, Third EditionCh05 – 8
Tracing recursion using indentation f(1) f(0) 1 output: 1 f(3) f(2) f(1) f(0) 1 2 f(1) f(0) 1 3 f(2) f(1) f(0) 1 2 f(1) f(0) 1 output: f(2) f(1) f(0) 1 2 f(1) f(0) 1 output: void f(int n) { if (n > 0) { f(n-1); System.out.print(n + " "); f(n-1); }
Tracing recursion using tree of calls void f(int n) { if (n > 0) { f(n-1); System.out.print(n + " "); f(n-1); } f(1) f(0) 1 f(0) output: 1 f(2) f(1) 2 f(0) 1 f(0) output: f(2) f(1) 2 f(1) f(0) 1 f(0) output: f(2) f(1) 2 f(1) f(0) 1 f(0) f(3) 3 f(1) f(0) 1 f(0) Data Structures and Algorithms in Java, Third EditionCh05 – 10
Excessive recursion nknk n-1 k-1 n-1 k + = 1 if k = 0 or k = n otherwise
Designing recursive methods: example ? 2 65 ? Data Structures and Algorithms in Java, Third EditionCh05 – 12
int add(int[] a, int last) { if (last == 0) return a[0]; else return add(a,last-1) + a[last]; } int add(int[] a) { // a.length ≥ 1 return add(a,a.length-1); } Designing recursive methods: example (cont’d) Data Structures and Algorithms in Java, Third EditionCh05 – 13