Professional Documents
Culture Documents
Time Complexity
Time Complexity
COMPLEXITY
MO3AZ
How to Measure Efficiency ?
MO3AZ
SAIF
Worst Case & BIG-O ?
5 8 1 4 3 9
MO3AZ
SAIF
Compute Time Complexity ?
MO3AZ
SAIF
Calculate F(n)
Most statements take constant time = 1 , except for loops and recursion.
Example : X = 5 - Sum += X - Print X - Read X - Conditions
Statements.
Loops :
F(n) = ( End - Start ) + 1
If the loop condition contains a sign (=) , the end is
incremented by 1.
MO3AZ
SAIF
Ignore constant factors and low order terms
f(n) = 4 O( f(n) ) = O(
1)
f(n) = 7n + 10 O( f(n)
) = O( n )
f(n) = 4+ n + 12 O( f(n) ) = O( )
MO3AZ
SAIF
EXAMPLES
MO3AZ
EXAMPLE ( 1 ) :
Public int sum(int n){
int total;
total=n*(n+1)/2 ; 1
Return total; 1
}
F(n) = 1 + 1 = 2
O( F(n) ) = O(1)
MO3AZ
SAIF
EXAMPLE ( 2 ) :
Public int sum (int n) {
int i , total;
total = 0; 1
For( i=1 ; i <= n ; i++ ){(n+1 - 1) + 1 = n + 1
total = total + i ; (n+1) - 1 = n
}
Return total ; 1
}
F(n) = 1 + ( n + 1 ) + n + 1 = 2n + 3
O( F(n) ) = O(n)
MO3AZ
SAIF
EXAMPLE ( 3 ) :
X=0; 1
( n - (-2) ) + 1 = n + 3
for(int i = -2 ; i < n ; i++){
x=x+i; (n+3)-1=n+2
y = x + 2 ; ( n + 3) - 1 = n + 2
}
Print(x); 1
MO3AZ
SAIF
EXAMPLE ( 4 ) :
Public int sum() {
int i , total;
total = 0 ; 1
for( i = 1 ; i <= 20 ; i++){ ( 20 + 1 - 1) + 1 =
total = total + i ; 21 - 1 =21
20
}
Return total ; 1
}
F(n) = 1 + 21 + 20 + 1 = 43
O( F(n) ) = O(1)
Execution time depends on the input size , no input in this
MO3AZ
code ! SAIF
EXAMPLE ( 5 ) :
int func(a[] ,n ){
int x = 5; 1
for(int i = 1 ; i <= n ; i++ ){( n + 1 - 1 ) + 1 = n + 1
for(int j = 1 ; j < n ; j++ ) ( n + 1 ) - 1 = n * ( n - 1 ) + 1 = n = n*n =
x = x + i + j ; ( ( n + 1 ) - 1 ) * ( n - 1 ) = n( n
𝒏 (𝒏 −𝟏)
print(x) -1)
} (1 - التانيةfor( * ( ال1 - االولىfor عدد تكراره = )الNested Forاللي جوه ال
}
}
MO3AZ