










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to recursive algorithms, their definition, approaches, format, and examples. Recursive algorithms are self-calling functions that solve a problem by breaking it down into smaller subproblems. The requirements for making recursion work, recursion vs. Iteration, and possible problems such as infinite loops and inefficiency.
Typology: Study notes
1 / 18
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)
An algorithm that calls itself
Solve small problem directly
Simplify large problem into 1 or more smallersubproblem(s) & solve recursively
Calculate solution from solution(s) for subproblem
Base case
If array is empty, return false
Recursive step
If 1
st
element of array is given value, return true
Skip 1
st
element and
recur
on remainder of array
Example (See ArrayExamples.java)
Base case
If array is empty, return
Recursive step
Skip 1
st
element and
recur
on remainder of array
Add
to result
int
fact
( int n ) {
if ( n == 0 ) return 1;
// base case
return n *
fact
(n-1);
// recursive step
Small version of problem solvable without recursion Strategy to simplify problem into 1 or more smallersubproblems Ability to calculate overall solution from solution(s)to subproblem(s)
Base case
Prove theorem is true for
n
= 0, and
Inductive step
Assume theorem is true for
n
(inductive hypothesis)
Prove theorem must be true for
n
Both have advantages
May be more efficient
No additional function calls Run faster, use less memory
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;
Move stack of disks between pegs Can only move top disk in stack Only allowed to place disk on top of larger disk
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
If recomputing solutions for subproblems
Fibonacci numbers
fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)