DSAP-Lecture 3 - Algorithm Analysis
DSAP-Lecture 3 - Algorithm Analysis
● Running Time
● Static and Run-time memory requirement.
● Worst Case
○ Defines the input for which the
algorithm takes maximum time
complete
● Best Case
○ Defines the input for which the
algorithm takes minimum time to
complete
● Average Case
○ Provides an average prediction
about the running-time of the
algorithm.
○ Needs to have understanding of
probability distribution of input data.
Seven Functions for analysing rate of growth
Approximation:
Examples:
Example:
Examples:
Cubic Function
Examples:
Polynomials:
Exponent Rules:
Examples:
Then
If
Then
Example:
Asymptotic Analysis with Big-Theta Notation
We say
if
Or
Example:
● In this case, the upper and lower bound of a
given function is same.
Arithmetic Series:
Geometric Series
Harmonic Series:
Others:
Few Examples of Asymptotic Analysis of Algorithms
Finding the maximum of a sequence
Constant time operations:
find_max(data) ~ O(n)
Finding the length of a list
How many times, we might update the “biggest” value?
len(data) ~ O(1)
Expected number of times we update the biggest value is a
accessing an element in a list Harmonic number
Data[j] ~ O(1);
Probability of updating the value of biggest:
k = 1, p = 1, certainty that update will occur the first time
k = 2, p = 1/2 ,
k = 3, p = 1/3
def find_max(data):
p = 1/2
p = 1/3
p=1
biggest = 0
for i in range(len(data)):
If data[i] > biggest:
biggest = data[i] a b c
Examples:
Ex 3:
Ex 1:
Ex 4:
Ex 2:
Running-time analysis for standard components
Consecutive n = 100
statements for i in range(0,n):
print(i)
for i in range(0,n):
For j in range(0,n):
print(i,j)
If-then-else if n == 1:
Print n
else:
For i in range(0,n)
Print i
Algorithms with Logarithmic growth rate
● n = len(s) ~ O(1)
● A = [0] * n ~ O(n)
● Outer loop (counter j) ~ O(n)
● Inner loop (counter i) is executed 1+2+3+
… + n times = n(n+1)/2 ~ O(n^2)
● Total Time = O(1) + O(n) + O(n^2) ~
O(n^2)
Two loops ~
● Initializing variables n and total uses O(1)
time
● Initializing the list A uses O(n) time
● Single for loop: counter j is updated in
O(n) time.
● Body of the loop is executed n times ~
O(n)
● Total running time of prefix_average3() is
in O(n) time.
Three-way Set Disjointness
Example 2:
Example:
Hypothesis: Let a and b be integers. If ab is odd,
then a is odd and b is odd.
Example: Fibonacci Function F(n)
● Induction
Consider the statement where a claim is
being made about an infinite set of
We claim that
numbers.
Base cases:
“q(n) is true for all n >= 1”
(n <= 2), F(1) < 2, F(2) = 2 < (4=2^2)