CSC 323: Algorithm Design

and Analysis
Analysis Basics
Non-Recursive Algorithms
• When we count operations that occur in
loops, we only need to determine how many
operations there are inside the loop and how
many times the loop is executed.
• Recall our Largest Value Algorithm.
• largest = list[1]
• for i = 2 to N do
– if list[i] > largest then
» largest = list[i]
– end if
• end for
Non-Recursive Algorithms
• So, our analysis of the Largest Value
algorithm has given us the following results:
• B(N) = 1; Best Case
• A(N) = (N + 1)/2; Average Case
• W(N) = N; Worst Case
• It is important to always be mindful of what
operation(s) were counted for the analysis.
Recursive Algorithms
• However, for recursive algorithms it is
not clear how many times an operation
will be done. This depends on:
– Recursive Calls
– Preparatory Work
– Concluding Work
Recursive Algorithms
• Consider the following recursive algorithm to
compute the factorial of a number, N.
• Factorial( N )
• if N == 1 then
• return 1
• else
• smaller = N – 1
• answer = Factorial( smaller )
• return (N * answer)
• end if
Recursive Algorithms
• How will this algorithm compute
Factorial ( 4 )?
• Factorial ( 4 )
• Call Factorial ( 3 ).
• Call Factorial ( 2 ).
• Call Factorial ( 1 ).
• Then?????
Recursive Algorithms
• To analyze recursive algorithms, we
use the following formula:
DIR( N ),
for N ≤ SizeLimit
REC( N ) =
DIV( N ) + ΣREC( smallerSizes[ i ] ) + COM ( N ),
for N > SizeLimit
Recursive Algorithms
• Thus, for our algorithm Factorial( N ), we
have:
0, for N = 1

Calc( N ) =

1 + Calc( N – 1 ) + 1, for N > 1

• What operation is being used for this
analysis?
• What is the time complexity of this algorithm?
Recursive Algorithms
• Recurrence relations can be directly
derived from a recursive algorithm.
• To determine the time complexity
(efficiency) of the algorithm we need to
convert the set of recursive algorithms
into closed form by removing the
recursive nature of the equations.
Recurrence Relations
• A recurrence relation is a recursive form
of an equation, for example:
T (1) =
3
T (n) = T (n −
1) +
2

• A recurrence relation can be put into an
equivalent closed form without the
recursion
Recurrence Relations