Finite description of steps for solving problem Problem types
Satisfying ⇒ find any legal solution Optimization ⇒ find best solution (vs. cost metric)
Approaches
Iterative Recursive ⇒ execute action in loop ⇒ reapply action to subproblem(s)
Recursive Algorithm
Definition
An algorithm that calls itself
Approach
1. Solve small problem directly 2. Simplify large problem into 1 or more smaller
subproblem(s) & solve recursively 3. Calculate solution from solution(s) for subproblem
Algorithm Format
1. Base case Solve small problem directly 2. Recursive step Simplify problem into smaller subproblem(s) Recursively apply algorithm to subproblem(s) Calculate overall solution
Example – Find
To find an element in an array
Base case If array is empty, return false Recursive step If 1st element of array is given value, return true Skip 1st element and recur on remainder of array Example (See ArrayExamples.java)
Example – Count
To count # of elements in an array
Base case If array is empty, return 0 Recursive step Skip 1st element and recur on remainder of array Add 1 to result
Example – Factorial
Factorial definition n! = n × n-1 × n-2 × n-3 × … × 3 × 2 × 1 0! = 1
To calculate factorial of n
Base case If n = 0, return 1 Recursive step Calculate the factorial of n-1 Return n × (the factorial of n-1)
Example – Factorial
Code
int fact ( int n ) { if ( n == 0 ) return 1; return n * fact(n-1); }
// base case // recursive step
Requirements
Must have
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
Designing a correct recursive algorithm Verify
1. Base case is
Recognized correctly Solved correctly 2. Recursive case Solves 1 or more simpler subproblems Can calculate solution from solution(s) to subproblems
Uses principle of proof by induction