Professional Documents
Culture Documents
CSC 323: Algorithm Design and Analysis
CSC 323: Algorithm Design and Analysis
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 ) =
Add( N ) =
Mult( Y ) =
Mult( Y ) =