4-Algorithm Analysis
4-Algorithm Analysis
T(n)=3n+4
It means this algorithm will take 3n+4 steps/statements for given value of n.
T(n,k)= 3nk+4n+4
9 Saba Anwar, Computer Science Department- CIIT Lahore 15/09/2024
Number of Steps/Statements
Advantages:
Is performed by studying a high-level description of the algorithm without need for
implementation.
Allows us to evaluate the relative efficiency of any two algorithms in a way that is
independent of the hardware and software environment.
Takes into account all possible inputs from best case to worst case.
Disadvantages:
Two different algorithm’s time cannot be directly compared
Solution?
Focus on growth rate /order of T(n), rather than it’s actual value
As n grows large
Terms with n changes more than terms which are constant
constants can be ignored for larger values of n as their contribution to T remains same
Terms with largest order of n becomes dominant than terms with lower order of n
It means lower order terms can be neglected for larger values of n to find growth order, because their contribution to
T grows at slower rate with compare to terms with higher order as n grows
Coefficients can also be neglected
They become irrelevant when comparing two functions with different order
12 Saba Anwar, Computer Science Department- CIIT Lahore 15/09/2024
Asymptotic Analysis
Asymptotic analysis is very useful for comparing algorithm efficiency. It
defines the growth order of algorithm rather than exact number of steps.
As steps are not universally defined, so T(n) is not very accurate approach to
measure time complexity. Moreover, every machine can take different time for
given steps.
So Asymptotic analysis categorize the algorithms on basis of their growth
order
T(n)= 3n+4O(n) T(n)=n2+5n+100O(n2) T(n)= 7n+1000O(n)
Algorithm with complexity Order n2 is slower than algorithm with Order n
O stands for Order, and is referred as Big-O
3. sum++;
1. for (i=1;i<n/2; i+=1)
4. print sum
2. print i*n
2. print i
4. print i
2. for(i=1;i<=n; i*=2)
3. print i
1. sum=0
2. for (i=0;i<n;++i)
3. for (j=0;j<n;++j)
1. for (i=1;i<n; i++)
4. sum++
2. for (j=1;j<i; j++)
5. print sum
3. print i
T(n)= 3n2+4n+4
24 Saba Anwar, Computer Science Department- CIIT Lahore 15/09/2024
Cubic
When algorithm time is directly proportional to cube of input size
Triple nested loops
1. sum=0
2. for (i=0;i<n;++i)
3. for (j=0;j<n;++j)
4. sum++
5. print sum
T(n)= 3n2+4n+4
25 Saba Anwar, Computer Science Department- CIIT Lahore 15/09/2024
Exponential
Involves dynamic programming and brute force algorithms
Few recursion problems also run in exponential time.
Exponential Rules: Given positive integers a, b, and c, we have: