Professional Documents
Culture Documents
Chapter 3
3.1 Introduction
Algorithm analysis is a method that measures the
efficiency of:
an algorithm, or
its implementation as a program,
when the input size becomes large.
Fast
2 n 3n
i 1
i
2 ,
i 1
i
2
6 ,
log n
1
n n log n ,
i 1
i 0
a i
1 a , for 0 a 1
n 1
, for a 1
n
1 1 n
a 1
i 1 2
i
1 n
2 ,
i 0
a
i
a 1
n2
n
n
i
n 1
i
2 n , 2 i
2 1
i 1 2 2 i 0
log n
2
i 0
i
2 log n 1
1 2n 1
n
1
Harmonic series n ,
i 1 i
log e n n 1 log e n
3.4 Calculating The Running
Time for a Program
Example:
a=b;
then T (n) is (1) .
Example:
sum=0;
for (i=1; i<=n; i++)
sum += n;
then T (n) is (c cn) , which is
simply (n) .
Example:
Sum = 0;
for (j=1; j<=n; j++)
for (i=1; i<=j; i++)
sum ++;
for (k=0; k<n; k++)
A[k] = k;
n
(c cj cn)
Then T (n) is j 1
, which can
n(n 1)
be simplified to ( c c cn) that is
2
(n ) .
2
Example:
Compare the asymptotic analysis for the following
two code segments:
sum1=0; sum2=0;
for (i=1;i<=n;i++) for (i=1;i<=n;i++)
for (j=1;j<=n;j++) for (j=1;j<=i;j++)
sum1++; sum2++;
then
1T ( n) is ( c1 c1 n 2
) , which is simply ( n 2
).
n
n(n 1)
T2 (n) is (c2 ic2 ) , which is ( c2 c 2 ) that
i 1 2
is simply ( n 2
).
Therefore, both code segments cost ( n 2
) , but the
second requires half the time of the first when both of
them are run on the same computer.
Example:
Compare the running time of the following two code
segments:
sum1=0; sum2=0;
for (k=1; k<=n; k*=2) for (k=1; k<=n; k*=2)
for (j=1; j<=n; j++) for (j=1; j<=k; j++)
sum1++; sum2++;
then,
log n
that is (n log n) .
log n
2
i
2
T ( n) is ( c 2 c 2 ) , which is (c2 c2 (2n 1)) that
i 0
is (n) .
3.5 Space Bounds
Storage space is also an important factor
for the program efficiency.