You are on page 1of 13

TIME

COMPLEXITY

MO3AZ
How to Measure Efficiency ?

Could measure time but want performance to be


machine independent. Expect to depend on size of
input , Size of input is often called "n”.

MO3AZ
SAIF
Worst Case & BIG-O ?

Searching for an element in array

5 8 1 4 3 9

Best Case Average Worst


First Element Middle
Case LastCase
Element
Elements
Notation of Worst Case : Big-O Notation.

- A mathematical notation that describes the complexity of your code.


Constant Logarithmic Linear Loglinear Polynomial Exponential Factorial
O( 1 ) O( log(n) ) O( n ) O( n log(n) ) O( ) O( ) O( n! )

MO3AZ
SAIF
Compute Time Complexity ?

 Calculate F(n) for each line.

 Ignore constant factors and low order terms.

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.

Iteration of statements inside the loop = loop iteration times - 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

F(n) = 1+n+3+n+2+n+2+1= 3n+9


O( F(n) ) = O(n)

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‫اللي جوه ال‬
}
}

F(n) = 1+ n+1 + + n( n-1 ) + n(n-1) = 3 + n - 2


O( F(n) ) = O( )
MO3AZ
SAIF
ANY QUESTIONS ?

MO3AZ

You might also like