The Basic of Algorithm
TII3201 - WEEK 09
Ika Nurlaili Isnainiyah, S.Kom., M.Sc.
SUMMARY of WEEK 09
Thinking recursively
Tracing execution of a recursive method
Writing recursive algorithms
Solving the Mathematical problem with recursion
Factorial
Powers
Iteration
Recursive Thinking
Recursion is:
A problem-solving approach, that can ...
Generate simple solutions to ...
Certain kinds of problems that ...
Would be difficult to solve in other ways
Recursion splits a problem:
Into one or more simpler versions of itself
3
Recursive Thinking: An Example
Strategy for processing nested dolls:
1. if there is only one doll
2. do what it needed for it
else
3. do what is needed for the outer doll
4. Process the inner nest in the same way
4
Recursive Thinking: The General Approach
1. if problem is small enough
2. solve it directly
3. else
4. break into one or more smaller subproblems
5. solve each subproblem recursively
6. combine results into solution to whole problem
5
Requirements for Recursive Solution
At least one small case that you can solve directly
A way of breaking a larger problem down into:
One or more smaller subproblems
Each of the same kind as the original
A way of combining subproblem results into an overall solution to the
larger problem
6
General Recursive Design Strategy
Identify the base case(s) (for direct solution)
Devise a problem splitting strategy
Subproblems must be smaller
Subproblems must work towards a base case
Devise a solution combining strategy
7
Recursive Design Example
Recursive algorithm for finding length of a string:
1. if string is empty (no characters)
2. return 0 base case
3. else recursive case
4. compute length of string without first character
5. return 1 + that length
Note: Not best technique for this problem; illustrates the approach.
8
Recursive Design Example: Code
Recursive algorithm for finding length of a string:
public static int length (String str) {
if (str == null ||
str.equals())
return 0;
else
return length(str.substring(1)) + 1;
}
9
Recursive Design Example: mystery
What does this do?
public static int mystery (int n) {
if (n == 0)
return 0;
else
return n + mystery(n-1);
}
10
Proving a Recursive Method Correct
Recall Proof by Induction:
1. Prove the theorem for the base case(s): n=0
2. Show that:
If the theorem is assumed true for n,
Then it must be true for n+1
Result: Theorem true for all n 0.
11
Proving a Recursive Method Correct (2)
Recursive proof is similar to induction:
1. Show base case recognized and solved correctly
2. Show that
If all smaller problems are solved correctly,
Then original problem is also solved correctly
3. Show that each recursive case makes progress towards the base case terminates
properly
12
Tracing a Recursive Method
Overall
result
length(ace)
3
return 1 + length(ce)
2
return 1 + length(e)
1
return 1 + length()
13
0
Tracing a Recursive Method (2)
14
Recursive Definitions of Mathematical
Formulas
Mathematicians often use recursive definitions
These lead very naturally to recursive algorithms
Examples include:
Factorial
Powers
15
Recursive Definitions: Factorial
0! = 1
n! = n x (n-1)!
If a recursive function never reaches its base case, a stack overflow error
occurs
16
Recursive Definitions: Factorial Code
public static int factorial (int n) {
if (n == 0) // or: throw exc. if < 0
return 1;
else
return n * factorial(n-1);
}
17
Recursive Definitions: Power
x0 = 1
xn = x xn-1
public static double power
(double x, int n) {
if (n <= 0) // or: throw exc. if < 0
return 1;
else
return x * power(x, n-1);
}
18
Recursion Versus Iteration
Recursion and iteration are similar
Iteration:
Loop repetition test determines whether to exit
Recursion:
Condition tests for a base case
Can always write iterative solution to a problem solved recursively, but:
Recursive code often simpler than iterative
Thus easier to write, read, and debug
19
Tail Recursion Iteration
When recursion involves single call that is at the end ...
It is called tail recursion and it easy to make iterative:
public static int iterFact (int n) {
int result = 1;
for (int k = 1; k <= n; k++) {
result = result * k;
}
return result;
}
20
Efficiency of Recursion
Recursive method often slower than iterative; why?
Overhead for loop repetition smaller than
Overhead for call and return
If easier to develop algorithm using recursion,
Then code it as a recursive method:
Software engineering benefit probably outweighs ...
Reduction in efficiency
Dont optimize prematurely!
21
END OF WEEK 09
Any questions?
Reference
Simple Program Design, A step-by- step Approach, LA Robertson, Cengage
Learning, 2006
C How to Program, 3rd ed, Deitel & Deitel, Prentice Hall, 2004