Analysis of Running Time of Algorithms (Best, Average and Worst Cases)
Analysis of Running Time of Algorithms (Best, Average and Worst Cases)
Analysis of Running Time of Algorithms (Best, Average and Worst Cases)
1
Recap
RAM model is used to measure the run time of an algorithm by counting the number of steps.
Space complexity of an algorithm refer to the amount of memory required to run.
Time complexity of an algorithm refer to its running time, which depends on input size.
Primitive operations refer to the unit of operation that can be identified in the pseudo-code
2
Counting Primitive Operations
Algorithm ArrayMax(A,n)
{An array A storing N integers
and find the largest element in A.}
4
Run Time Analysis (Cont !!!)
int method()
{
int a,b,large; --------- c1
a=2; --------- c2 Run Time Complexity will be =
b=3; --------- c2
c1+c2+c2 + c3 +c2 + c2 + c4
if(a>b) -------- c3
large=a; -------- c2 = c1 + 4c2 + c3 +c4 (as all constants)
else =C
large = b; ------- c2 Note:- =You can say there should be
printf(“Large number is %d”, large);
3c2 instead of 4c2 (Coefficient have
Return 0; ---------- c4
}
no impact)
5
Run Time Analysis (Cont !!!)
int method()
{
int I, codd, ceven, a[5]={5,4,3,2,1}; --------- c1
ceven=0;codd=0; ----------- c2
for(i=0;i<=4;i++) ------ c3 Run Time Complexity will be = c1+c2
if(a[i]%2==0) -------- c4 + n* (c3 +c4 + c5)+ c6
ceven++;-------- c5 = c1 + c2 + n*c +c6
else
= n*c + c
codd++; ------- c5
= n
printf(“Total evens %d and Total Odd %d”, ceven, codd);
Return 0; ---------- c6
}
6
Run Time Analysis (Cont !!!)
int method()
{
int I, a[5]; --------- c1
N for(i=0;i<=4;i++) ------ c2
Scanf(“%d”, &a[i]);
Run Time Complexity will be = c1 + n
for(i=0;i<=4;i++) * c2 + n*(c2+c3) + n * c2 + c4
A[i]=a[i]+5; ----------- c3 = c1 + 2n*c2 + n * c
N
for(i=0;i<=4;i++) = c1 + n * c + n * c
N
print(“%d”, a[i]); = 2n*c +c1
return 0; ---------- c4 = 2n
} =n
7
Run Time Analysis (Cont !!!)
10
Types of Algorithm Complexity
(Example: Linear Search)
5 7 2 6 9 12 1
Average Case
Complexity
Best Case
Complexity
N
(input size)
12
Relationship between complexity types and
running time of Algorithms
Worst case
– Provides an upper bound on running time
– An absolute guarantee that the algorithm would not run longer, no matter what the
inputs are
Best case
– Provides a lower bound on running time
– Input is the one for which the algorithm runs the fastest
Running Time
80
to determine.
60
We focus on the worst case
40
running time.
– 20
Easier to analyze
– 0
Crucial to applications such as 1000 2000 3000 4000
games, finance and robotics Input Size
14
Home Work
Exercise-1.
– Write a pseudo code which find the sum of two 3*3 matrics and then calculate its running time.
Exercise-2.
– Write a pseudo code which read a number N and print whether it is prime or not . After that, calculate the run time complexity
15
Summary
16
In Next Lecturer
In next lecture, we will talk about the asymptotic analysis fro comparisons of algorithms.
17