1.Complexity
1.Complexity
Guideline 1
int a = 4+5;
Expressions and
assignment statements
char b =‘a’;
Memory Management
int * a = new int;
statements delete a;
Student a,b;
Memory Management
statement of object Student * a = new Student;
delete a;
Assignment statement
of object a = b;
5
Guideline 5: Loops
The running time of a loop is, at most, the running time of the
statements inside the loop (including tests) multiplied by the number
of iterations.
6
Guideline 6: Nested loops
7
Guideline 7: Consecutive statements
8
Guideline 8: If-then-else statements
if( exp)
statements1;
else
statements2;
Cost is the number of steps corresponding to exp, statements1 and
statements2.
10
Example
► If T(n) = 7n+100
► What is T(n) for different values of n???
n T(n) Comment
1 107 Contributing factor is 100
5 135 Contributing factor is 7n and 100
10 170 Contributing factor is 7n and 100
100 800 Contribution of 100 is small
1000 7100 Contributing factor is 7n
10000 70100 Contributing factor is 7n
106 7000100 What is the contributing factor????
When approximating T(n) we can IGNORE the 100 term for very
large value of n and say that T(n) can be approximated by 7(n)
Example 2
1 0 0 1 1 2
2 1 2 4 8 4
8 3 24 64 512 256
void main(){
const int n= 5;
int array[n]={3,5,9,6,1};
sortArray(array,n);
print(array,n);
}
void main(){
const int n= 5;
int array[n]={3,5,9,6,1};
for(int i =0; i <n; i++)
O(n3 O(n2) sortArray(array,n);
) print(array,n);
}
Iteration 2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Iteration 3
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Low High
Mid
Iteration 4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15