






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Satisfying โ find any legal solution Optimization โ find best solution (vs. cost metric)
Iterative โ execute action in loop Recursive โ reapply action to subproblem(s)
Recursive Algorithm
An algorithm that calls itself
Algorithm Format
Solve small problem directly
Simplify problem into smaller subproblem(s) Recursively apply algorithm to subproblem(s) Calculate overall solution
Example โ Factorial
n! = n ร n-1 ร n-2 ร n-3 ร โฆ ร 3 ร 2 ร 1 0! = 1
Base case If n = 0, return 1 Recursive step Calculate the factorial of n- Return n ร (the factorial of n-1)
Example โ Factorial
int fact ( int n ) { if ( n == 0 ) return 1; // base case return n * fact(n-1); // recursive step }
Requirements
Small version of problem solvable without recursion Strategy to simplify problem into 1 or more smaller subproblems Ability to calculate overall solution from solution(s) to subproblem(s)
Making Recursion Work
Recursion vs. Iteration
Higher overhead Time to perform function call Memory for activation records (call stack) May be simpler algorithm Easier to understand, debug, maintain Natural for backtracking searches Suited for recursive data structures Trees, graphsโฆ
Example โ Factorial
int fact ( int n ) { if ( n == 0 ) return 1; return n * fact(n-1); }
Recursive algorithm is closer to factorial definition
int fact ( int n ) { int i, res; res = 1; for (i=n; i>0; i--) { res = res * i; } return res; }
Example โ Towers of Hanoi
Move stack of disks between pegs Can only move top disk in stack Only allowed to place disk on top of larger disk
Example โ Towers of Hanoi
Base case If n = 1, move disk from X to Y Recursive step
Recursive algorithm is simpler than iterative solution
Possible Problems โ Infinite Loop
If recursion not applied to simpler problem
int bad ( int n ) { if ( n == 0 ) return 1; return bad(n); }
Will infinite loop Eventually halt when runs out of (stack) memory Stack overflow
Possible Problems โ Inefficiency
If recomputing solutions for subproblems
Fibonacci numbers fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
Possible Problems โ Inefficiency
If n is 0 or 1, return 1 Else compute fibonacci(n-1) and fibonacci(n-2) Return their sum
Computes fibonacci(1) 2n^ times
Iteration Dynamic programming Will examine different algorithm strategies laterโฆ