2-Analysis of Algorithm
2-Analysis of Algorithm
Algorithm Analysis
❑THEOREM:
If t1(n) ∈ O(g1(n)) and t2(n) ∈ O(g2(n)), then t1(n) + t2(n) ∈ O(max{g1(n), g2(n)}).
❑For an algorithm that comprises two consecutively executed parts, the algorithm’s overall
efficiency is determined by the part with a higher order of growth i.e., its least efficient part
❑E.g., we can check whether an array has equal elements by the following two-part algorithm:
▪ first, sort the array by applying some known sorting algorithm;
▪ second, scan the sorted array to check its consecutive elements for equality
Using Limits for Comparing Orders of Growth
❑Computing the limit of the ratio of two functions
❑ Note that the first case mean that t (n) ∈ O(g(n)), the second case means that t (n) ∈ Θ(g(n))
and the last mean that t (n) ∈ Ω(g(n))
❑The limit-based approach can take advantage of the powerful calculus techniques developed for
computing limits
▪ L’Hopital’s rule
▪ Stirling’s formula
Analysis of Non-recursive Algorithms
❑Consider the problem of finding the value of the largest element in a list of n numbers. For
simplicity, we assume that the list is implemented as an array. The following is pseudocode of a
standard algorithm for solving the problem.
❑The number of element comparisons depends not only on n but also on whether there are equal
elements in the array and, if there are, which array positions they occupy
❑Worst case analysis
▪ Two kinds of worst-case inputs - arrays with no equal elements and arrays in which the last two
elements are the only pair of equal elements.
Analysis of recursive Algorithms
❑E.g., Compute the factorial function F(n) = n! for an arbitrary nonnegative integer n