Professional Documents
Culture Documents
Chapter 2
www.CareerMonk.com
ANALYSIS OF ALGORITHMS
Introduction
This chapter will create the base for remaining all chapters. The objective of this chapter is to
tell you the importance of analysis of algorithms, their notations, relationships and solving as
many problems as possible. We first concentrate on understanding the importance of analysis
and then slowly move towards analyzing the algorithms with different notations and finally,
the problems. After completion of this chapter you will get the confidence in finding the
complexities of any given algorithm (especially recursive functions).
What is algorithm?
Just to understand better, let us consider the problem of preparing an omelet. For preparing
omelet, general steps which we follow are:
1) Get the frying pan.
2) Get the oil.
a. Do we have oil?
i. If yes, put it in the pan.
ii. If no, do we want to buy oil?
1. If yes, then go out and buy.
2. If no, we can terminate.
3) Turn on the stove.
4) Etc...
The above steps says that, for a given problem (in this case, preparing an omelet), giving step
by step procedure for solving it. So, the definition of algorithm can be given as:
An algorithm is the stepstep-byby-step instructions to a given problem.
One important thing to remember while writing the algorithms is, we do not have to prove
each step. Also, all algorithms involve the basic elements which we have discussed in
chapter.
www.CareerMonk.com
Size of an array
Polynomial degree
Number of elements in a matrix
Number of bits in the binary representation of the input
Vertices and edges in a graph
since the number of statements varies with the programming language
as well as the style of the individual programmer.
Ideal Solution?
Solution
www.CareerMonk.com
Let us assume that we expressed running time of given algorithm as a function of the input
size (i.e., ). We can compare these different functions corresponding to running times
and this kind of comparison is independent of machine time, programming style, etc..
'1
Example
Constant
'
Logarithmic
'
Linear
'
'
'2)
Quadratic
Cubic
Exponential
Matrix Multiplication
The Towers of Hanoi problem
'
"
(
www.CareerMonk.com
!
D
e
c
r
e
a
s
i
n
g
4)
2)
"
log
log !
2./0 )
"
1
R
a
t
e
s
O
f
G
r
o
w
t
h
log log
1
Types of Analysis
Assume that we have an algorithm for a problem and want to know on what inputs the
algorithm is taking less time (performing well) and on what inputs the algorithm is taking
huge time.
We have already seen that an algorithm can be represented in the form of an expression.
That means we represent the algorithm with multiple expressions: one for case where it is
taking the less time and other for case where it is taking the more time. In general the first
69 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
case is called the best case for the algorithm and second case is called the worst case for the
algorithm.
To analyze an algorithm we need some kind of syntax and that forms the base for asymptotic
analysis/notation. There are three types of analysis:
Worst case
o Defines the input on which the algorithm is taking huge time.
o Input is the one for which the algorithm runs the slower.
Best case
o Defines the input on which the algorithm is taking lowest time.
o Input is the one for which the algorithm runs the fastest.
Average case
o Provides a prediction about the running time of the algorithm
o Assumes that the input is random
Lower Bound <= Average Time <= Upper Bound
For a given algorithm, we can represent best case, worst case, average case analysis in the
form of expressions. As an example, let be the function which represents the given
algorithm. Then, the following expression for best case and worst case.
= " & 500, for worst case
= & 100 & 500 , for best case
Similarly, for average case too. The expression defines the inputs with which the algorithm
takes the average running time (or memory).
Asymptotic notation?
Having the expressions for best case, average case and worst case, to find the upper bounds
and lower bounds for each of them: for all the three cases we need to identify the upper
bound, lower bounds. In order to represent these upper bound and lower bounds we need
some syntax and that creates the base for following discussion.
For the below discussions, let us assume that the given algorithm is represented in the form
of function .
BigBig-O notation
70 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
This notation gives the upper bound of the given function. Generally we represent it
as = '. That means, at larger values of , the upper bound of is .
For example, if = & 100" & 10 & 50 is the given algorithm, then is .
That means gives the maximum rate of growth for at larger values of .
Now, let us see the ' Gnotation with little more detail. ' Gnotation defined as ' =
H: there exist positive constants and nJ such that 0 K K for all L J M.
is an asymptotic tight upper bound for . Our objective is to give some rate of
growth which is greater than given algorithms rate of growth .
In general, we do not consider lower values of . That means the rate of growth at lower
values of is not important. In the below figure, J is the point from which we consider
the rate of growths for a given algorithm. Below J the rate of growths may be different.
Rate of Growth
Input Size,
J
BigBig-O Visualization
'
3 & 100,
100, 2
G 1, 3, .
'1
100,1000,
200,1,20, .
'
5, 3 G 100,
2 G 1, 100, 100,
.
'"
, 5 G 10, 100,
" G 2 & 1, 5,
.
"
' is the set of functions with smaller or same order of growth as . For example,
' " includes '1, ', ' etc..
71 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
Note: Analyze the algorithms at larger values of only. What this says is, below J we do
not care for rates of growth.
BigBig-O examples
ExampleExample-1 Find upper bound for = 3 & 8
Solution: 3 & 8 K 4, for all L 1
3 & 8 = ' with c = 4 and nJ = 8
No uniqueness?
There is no unique set of values for J and in proving the asymptotic bounds. Let us
consider, 100 & 5 = '" . For this function there are multiple J and .
72 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
Solution1: 100 & 5 K 100 & = 101 K 101" for all L 5, J = 5 and =
101 is a solution.
Solution2: 100 & 5 K 100 & 5 = 105 K 105" for all L 1, J = 1 and
= 105 is also a solution.
OmegaOmega- notation
Similar to above discussion, this notation gives the tighter lower bound of the given
algorithm and we represent it as = . That means, at larger values of , the
tighter lower bound of is .
For example, if = 100" & 10 & 50, is " .
The notation as be defined as = H: there exist positive constants and
nJ such that 0 K K for all L 0 M. is an asymptotic lower bound for
. is the set of functions with smaller or same order of growth as .
Rate of Growth
Examples
J
Input Size,
www.CareerMonk.com
ThetaTheta- notation
This notation decides whether the upper and lower bounds of a given function are same or
not. The average running time of algorithm is always between lower bound and upper
bound. If the upper bound (') and lower bound () gives the same result then V notation
will also have the same rate of growth. As an example, let us assume that = 10 & is
the expression. Then, its tight upper bound is '. The rate of growth in best case
is = '. In this case, rate of growths in best case and worst are same. As a result, the
average case will also be same.
Note: For a given function (algorithm), if the rate of growths (bounds) for ' and are not
same then the rate of growth V case may not be same.
c"
Rate of Growth
cY
Input Size,
J
Now let us see the definition of V notation. It is defined as X = H: there exist
positive constants Y , " and nJ such that 0 K Y K K " for all L 0 M.
is an asymptotic tight bound for . V is the set of functions with the same
order of growth as .
Examples
ExampleExample-1 Find bound for =
)Z
"
G"
www.CareerMonk.com
)Z
[
)Z
"
)Z
"
./0 )
, L n0 Impossible
Important Notes
For each of the analysis (best case, worst case and average) we try to give upper bound (')
and lower bound () and average running time V. Also, from the above examples, it should
also be clear that, for a given function (algorithm) getting upper bound (') and lower bound
() and average running time (V) may not be possible always.
For example, if we are discussing the best case of an algorithm, then we try to give upper
bound (') and lower bound () and average running time (V).
In the remaining chapters we generally concentrate on upper bound (') because knowing
lower bound () of an algorithm is of no practical importance and we use notation if upper
bound (') and lower bound () are same.
www.CareerMonk.com
] . In other terms, is the asymptotic curve for . For this reason, we
call our analysis as ] .
www.CareerMonk.com
{
m = m + 2; //constant time
}
//outer loop executed n times
for (i=1; i<=n; i++)
{
//inner loop executed n times
for (j=1; j<=n; j++)
{
k = k+1; //constant time
}
}
Total time = J & Y & " " = ' " .
4) If
If--thenthen-else statements:
statements: Worst-case running time: the test, plus either the then part or
the else part (whichever is the larger).
//test: constant
if (length ( ) != otherStack. length ( ) )
{
return false; //then part: constant
}
else
{
// else part: (constant + constant) * n
for (int n = 0; n < length( ); n++)
{
// another if : constant + constant (no else part)
if (!list[n].equals(otherStack.list[n]))
//constant
return false;
}
}
Total time = J & Y & " & ( _ = '.
5) Logarithmic complexity:
complexity: An algorithm is ' if it takes a constant time to cut the
problem size by a fraction (usually by ).
77 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
Let us say the loop is executing some a times. That means at a G step 2b = n and we
come out of loop. So, if we take logarithm on both sides,
c2b d =
2 =
= //if we assume base-2
Note: Similarly, for the below case also the worst case rate of growth is '. That means,
the same discussion holds good for decreasing sequence also.
for (i=n; i<=1;)
{
i = i/2;
}
Another example algorithm (binary search): finding a word in a dictionary of pages
Properties of notations
Transitivity: = and = = . Valid for O
and also.
Reflexivity: = . Valid for O and also.
Symmetry: = if and only if = .
78 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
Logarithms
n
jklo
m
jklo
Arithmetic series
)
uvY
Geometric series
& 1
2
xn{1 G 1
r = 1 & x & x & =
x R 1
xG1
n
kv1
Harmonic series
)
1
1
1
r = 1 & & & log
s
2
ivY
)
ivY
)
ivY
1
|{Y
]&1
www.CareerMonk.com
~ = 2~ & '
2
The following theorem can be used to determine the running time of divide and conquer
algorithms. For a given program or algorithm, first we try to find the recurrence relation for
the problem. If the recurrence is of below form then we directly give the answer without
fully solving it.
If the reccurrence is of the form ~ = ~ & Xs| , where L 1, 1, s L 0
)
p
and ] is a real number, then we can directly give the answer as:
If a
2) If a =
a.
b.
c.
3) If a <
a.
b.
1)
ProblemProblem-1
ProblemProblem-2
ProblemProblem-3
ProblemProblem-4
Solution:
Solution: ~ = 3~ /2 & " = ~ = X" (Master Theorem Case 3.a)
Solution:
Solution: ~ = 4~ /2 & " = ~ = X" (Master Theorem Case 2.a)
Solution:
Solution: ~ = ~/2 & 2) = X2) (Master Theorem Case 3.a)
Solution:
Solution: ~ = 2) ~/2 & ) => Does not apply ( is not constant)
ProblemProblem-5
ProblemProblem-6
ProblemProblem-7
ProblemProblem-8
ProblemProblem-9
www.CareerMonk.com
Solution:
Solution: ~ = 16~ /4 & = ~ = X" (Master Theorem Case 1)
Solution:
Solution: ~ = 2~/2 & = ~ = X" (Master Theorem Case 2.a)
Solution:
Solution: ~ = 2~/2 & / = ~ = Xloglogn (Master Theorem Case
2.b)
Solution:
Solution: ~ = 2~/4 & J.[Y = ~ = 'J.[Y (Master Theorem Case 3.b)
Solution:
Solution: ~ = 0.5~/2 & 1/ = Does not apply ( < 1)
Solution:
Solution: ~ = 6~/3 & " = ~ = X" (Master Theorem Case 3.a)
Solution:
Solution: ~ = 64~/8 G " = Does not apply (function is not positive)
Solution
Solution: ~ = 7~/3 & " = ~ = X" (Master Theorem Case 3.as)
Solution:
Solution: ~ = 4~/2 & = ~ = X" (Master Theorem Case 1)
Solution:
Solution: ~ = ~/2 & 2 G = Does not apply. We are in Case 3, but the
regularity condition is violated. (Consider = 2k, where s is odd and arbitrarily large. For
any such choice of , you can show that = 3/2, thereby violating the regularity
condition.)
www.CareerMonk.com
Solution:
Solution: ~ = 16~ /4 & ! = ~ = X! (Master Theorem Case 3.a)
Solution:
Solution: ~ = 2~ /2 & = ~ = X (Master Theorem Case 1)
Solution:
Solution: ~ = 3~ /2 & = ~ = X jkl( (Master Theorem Case 1)
Solution:
Solution: ~ = 3~ /3 & = ~ = X (Master Theorem Case 1)
Solution:
Solution: ~ = 4~ /2 & = ~ = X " (Master Theorem Case 1)
Solution:
Solution: ~ = 3~ /4 & = ~ = X (Master Theorem Case 3.a)
Solution:
olution: ~ = 3~ /3 & /2 = ~ = X (Master Theorem Case 2.a)
c,
aTn G b & fn,
if K 1
if 1
Ocn d,
{Y
~ = Ocn d,
O
n
a
,
if a < 1
if a = 1
if a 1
www.CareerMonk.com
Problems on Algorithms
Algorithms Analysis
Note: From the following problems, try to understand in what cases we get different
complexities (', ', ' etc..).
3~ G 1, 0,
1,
Note: We can directly use the } master theorem for this problem.
2~ G 1 G 1, 0,
1,
Solution:
Solution: Let us try to solve this function with substitution.
~ = 2~ G 1 G 1
So the complexity is '1. Note that while the recurrence relation looks exponential the
solution to the recurrence relation here gives a different result.
83 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
ProblemProblem-24 What is the running time of the following function (specified as a function of
the input value n)
void Function(int n)
{
int i=1 ;
int s=1 ;
while( s n)
{
i++ ;
s= s+i ;
print(\*");
}
}
Solution:
Solution: Consider the comments in below function:
void Function (int n)
{
int i=1 ;
int s=1 ;
// s is increasing not at rate 1 but i
while( s n)
{
i++ ;
s= s+i ;
print(*");
}
}
We can define the terms according to the relation = Y & i. The value of increases
by one for each iteration. So the value contained in at the iteration is the sum of the
first positive integers. If s is the total number of iterations taken by the program, then the
while loop terminates once.
1 & 2 & ...& s =
ss & 1
L s = '.
2
www.CareerMonk.com
www.CareerMonk.com
www.CareerMonk.com
{
//constant time
if ( n == 1 ) return ;
//outer loop execute n times
for( i = 1 ; i <= n ; i + + )
{
// inner loop executes only time due to break statement.
for( j= 1 ; j <= n ; j + + )
{
print(*" ) ;
break;
}
}
}
The complexity of the above function is '. Even though the inner loop is bounded by n,
but due to the break statement it is executing only once.
ProblemProblem-29 Write a recursive function for the running time ~ of the function function,
whose code is below. Prove using the iterative method that ~ = X" .
function( int n )
{
if ( n == 1 ) return ;
for( i = 1 ; i <= n ; i + + )
for( j = 1 ; j <= n ; j + + )
print(*" ) ;
function( n-3 );
}
Solution:
Solution: Consider the comments in below function:
function (int n)
{
//constant time
if ( n == 1 ) return ;
//outer loop execute n times
for( i = 1 ; i <= n ; i + + )
//inner loop executes n times
for( j = 1 ; j <= n ; j + + )
87 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
//constant time
print(*" ) ;
function( n-3 );
}
The recurrence for this code is clearly T = ~ G 3 & " for some constant 0
since each call prints out " asterisks and calls itself recursively on n - 3. Using the iterative
method we get:
~ = ~ G 3 & "
Using the } master theorem, we get ~ = X( .
Solution:
Solution: Using Divide and Conquer master theorem, we get ' " .
~ K 1 _
ProblemProblem-33 Prove that the running time of the code below is .
Read(int n);
{
int k = 1 ;
while( k < n )
k = 3k;
}
www.CareerMonk.com
Solution:
Solution: The while loop will terminate once the value of s is greater than or equal to the
value of . Since each loop the value of s is being multiplied by 3, if i is the number of
iterations, then s has the value of 3i after i iterations. That is the loop is terminated upon
reaching i iterations when 3 n i log ( , which shows that = .
1,
= 1
~ =
~ G 1 & G 1, L 2
Solution: By iteration:
"
vY
Note: We can directly use the } master theorem for this problem.
Notice ~ has two recurrence calls indicating a binary tree. Each step recursively calls the
program for only reduced by 1 and 2, so the depth of the recurrence tree is '. The
number of leaves at depth is 2 since this is a full binary tree, and each leaf takes at least
'1 computation for the constant factor. So, the running time is clearly exponential in .
www.CareerMonk.com
Its running time is ^ = 'Z since the inner loop is same as that of G
24].
Solution:
Solution: Using the logarithmic property that, f = f & . We can see that this
problem is equivalent to
)
= 1 ^ 2 ^ ^
= !
K )
K
ProblemProblem-38 What is the running time of the following recursive function (specified as a
www.CareerMonk.com
f( );
}
Solution:
olution: Consider the comments in below function:
function (int n)
{
//constant time
if (n 1)
return ;
int i;
f(();
We can assume that for asymptotical analysis k = k = k for every integer s L 1. The
)
recurrence for this code is ~ = 3~ ( & X1.
Using master theorem, we get ~ = X.
function of the input value ? First write a recurrence formula, and show its solution
using induction.
function(int n)
{
if (n 1)
return;
for (i=1 ; i 3 ; i++ )
function (n 1).
}
ProblemProblem-39 What is the running time of the following recursive function (specified as a
Solution:
Solution: Consider the comments in below function:
function (int n)
{
//constant time
if (n 1)
91 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
return;
//this loop executes 3 times with recursive call of n-1 value
for (i=1 ; i 3 ; i++ )
function (n 1).
}
The requires constant time (call it '1). With the ], we neglect the
loop overhead and only count the three times that the function is called recursively. This
implies a time complexity recurrence
~ = , K 1;
= & 3~ G 1, 1.
Now we use repeated substitution to guess at the solution when we substitute k times:
~ = & 3~ G 1
Using the } master theorem, we get ~ = X3) .
ProblemProblem-40 Write a recursion formula for the running time ~ of the function f, whose
code is below. What is the running time of , as a function of ?
function (int n)
{
if (n 1)
return;
int i = 1 ;
for(i = 1; i < n; i + +)
print(*);
function ( 0.8n ) ;
}
Solution:
Solution: Consider the comments in below function:
function (int n)
{
//constant time
if (n 1)
return;
//constant time
int i = 1 ;
// this loop executes times with constant time loop
92 Analysis of Algorithms | CareerMonk Publications
www.CareerMonk.com
"
"
www.CareerMonk.com
} = 2} & 1
2
www.CareerMonk.com
ProblemProblem-45 Analyze the running time of the following recursive procedure as a function of
n. You may assume that each assignment or division takes unit time.
void function(int n)
{
if ( n < 2 )
return;
else
counter = 0;
for i = 1 to 8 do
)
function ( );
"
for I =1 to ( do
counter = counter + 1;
}
Solution: Consider the comments in below function and let us refer to the running time of
function (n) as T(n).
void function(int n)
{
//constant time
if ( n < 2 )
return;
else
counter = 0;
// this loop executes 8 times with n value half in every call
for i = 1 to 8 do
)
function ( );
"
}
~ can be defined as follows:
~ = 1 < 2,
= 8~ & ( & 1 .
2
Using the master theorem gives, ~ = XjklZ log = ( log n.
www.CareerMonk.com
"
"
until n 1
)
"
www.CareerMonk.com
for( j = 1 ; j n ; j * = 2 )
print( * ) ;
}
Complexity of above program is : '.
function( " );
function( " );
www.CareerMonk.com
Note:
Note: With these examples, I hope you got an understanding of analysis of algorithms. In this
chapter, try to understand when do we get different complexities like: ', ',
', '" , '2) etc so that it will be clear when we refer them in remaining chapters.