Lecture 3
Lecture 3
Algorithms
Lecture 3
Time
Why time complexity? complexity
• We have to fix up the time limit for a program to avoid indefinite use of computer
time.
• From the time complexity of program we can decide whether the program or
program module needs to be redesigned.
Time complexity of a program is
Function statement 0 because cost included Jump statement (break, 1 if not based on
in invocation continue, goto, return) instance characteristic
A Few language specific important points
regarding
Statement TC
Steps/Cost Frequency Total step cost
for(i = 1; i <= n; ++i) 1 n+1 n+1
for(i = 0; i < n; ++i) 1 n+1 n+1
for(i = 0; i <= n; ++i) 1 n+2 n+2
for(i = 1; i < n; ++i) 1 n n
for(i = 5; i <= n; ++i) 1 n-4+1 = n-3 n-3
OR
Statement Steps/Cost Frequency Total step cost
for(i = 1; i <= n; ++i) 1, 1, 1 1, n+1, n 1+n+1+n = 2n+2
for(i = 0; i < n; ++i) 1, 1, 1 1, n+1, n 1+n+1+n = 2n+2
for(i = 0; i <= n; ++i) 1, 1, 1 1, n+2, n+1 1+n+2+n+1 = 2n+4
for(i = 1; i < n; ++i) 1, 1, 1 1, n, n-1 1+n+n-1 = 2n
for(i = 5; i <= n; ++i) 1, 1, 1 1, n-4+1, n-5 1+n-3+n-5 = 2n-7
int num; 1 1 1
cin>>num; 1 1 1
if (num%2 1 1 1
== 0) 1 n+1 n+1
for(i = 1;
i <= n; +
+i)
Analysis
• num may or may not be divided on 2.
• So lets take average and we say there are 50% chances the condition will be true
• ½ (n+1) is the average frequency of execution of loop statement
• So total program steps on the average = 1+1+1+ ½ (n+1) = 2.5+ ½ n
Logarithmic time
complexity Steps/Cost
Statement Frequency Total step cost