Algo Analysis
Algo Analysis
Algo Analysis
COLLEGE OF ENGINEERING
Karvenagar, Pune
Accredited with ‘A’ Grade by NAAC
Unit - 01
Part - B
Algorithm Analysis
DSA
Complexity
• Space
• Time
j
SpaceComplexity
j
SpaceComplexity
j
SpaceComplexity
j
SpaceComplexity
• Data space
• very much dependent on the computer architecture and
compiler
char 1 float 4
short 2 double 8
int 4 long double 10
long 4 pointer 2
Unit: bytes
j
SpaceComplexity
• Data space
j
SpaceComplexity
j
TimeComplexity
• execution time
j
Time Complexity
Best time
The minimum amount of time required by the algorithm for any
input of size n.
Seldom of interest.
Average time
The average amount of time required by the algorithm over all
inputs of size n
j
Worst Case Complexity
• Of the three cases the really only useful case (from the
standpoint of program design) is that of the worst case.
j
FrequencyCount
j
FrequencyCount-Example
Examine a piece of code and predict the number of
instructions to be executed
for each instruction predict how mant times each will be encountered as the
code runs
j
FrequencyCount
Program 1 Program 2
x := x + 1 FOR i := 1 to n
DO
x := x + 1
END
Program 3
FOR i := 1 to n
DO
FOR j := 1 to n
DO
x := x + 1
END
END
j
FrequencyCount
Program 1:
– statement is not contained in a loop (implicitly or explicitly)
– Frequency count is 1
Program 2
– statement is executed n times
Program 3
– statement is executed n2 times
j
FrequencyCount
an algorithm
j
FrequencyCount :Example 1
sum = 0.0;
for (int i = 0; i < n; i++) {
sum += array[i]; // </ / / / / a primitive operation
}
Ignoring the update to the loop variable i, we note the marked
statement above is executed n times, so the cost function is
C(n)=n.
j
FrequencyCount:Example 2
sum = 0.0;
for (int i = 0; i < n; i += 2) {
sum += array[i]; // </ / / / / a primitive operation
}
Here however, since the counter variable i is going up by 2 with
each pass through the loop, the number of times the marked
statement above gets executed this time is halved / / leading to
C(n)=n/2.
j
FrequencyCount:Example 3
j
FrequencyCount:Example 4
j
Classifying Functions
j
Asymptotic Notation
j
OrderofGrowth
j
OrderofGrowth
The algorithms are grouped into groups according to the order of growth
of the their time complexity functions, which include:
O(1) < O(logN) < O(N) < O(NlogN) < O(N2) < O(N3) < … < O(eN)
j
BigOhNotation
j
BigOhNotation
need to run
j
BigOhNotation
j
PracticalComplexities
logn n nlogn n2 n3 2n
0 1 0 1 1 2
1 2 2 4 8 4
2 4 8 16 64 16
3 8 24 64 512 256
4 16 64 256 4096 65536
5 32 160 1024 32768 4294967296
j
BigOhNotation - Example
f(n) = 10n + 5
f(n) = 3n2 + 4n + 1
f(n) = 5n2
f(n) = 7n ~ 2