05 Analysis
05 Analysis
Other References
Data Structures 2
Asymptotic Behavior
Data Structures 3
Big-Oh Notation
Data Structures 4
x = 1:10;
y1 = x.*x;
y2 = 2*(x.*x)+x+1;
y3 = 3*(x.*x);
plot(x,y1,'r')
hold on
plot(x,y2,'g')
plot(x,y3,'b')
Data Structures 6
The common comparisons
Name Big-Oh
Constant O(1)
Log log O(log log N)
Increasing cost
Logarithmic O(log N)
Log squared O((log N)2)
}
Linear O(N)
N log N O(N log N)
Polynomial time
Quadratic O(N2)
Cubic O(N3)
Exponential O(2N)
Data Structures 7
n = 1:100;
y1 = n-n+1;
y2 = log2(n);
y3 = n;
y4 = n.*log2(n);
y5 = n.^2;
y6 = 2.^n;
from bigo.m
Data Structures 9
Big-Oh Notation
TA(N) = O(N2)
N2
TA(N) is O(N2)
because 50N N2
TA(N) = 50N for N 50.
So N2 is an upper
bound. But it's not a
very tight upper
bound.
Input Size N
Data Structures 10
Big-Oh and Omega
Data Structures 11
Theta and Little-Oh
T(N) = (f(N)) iff T(N) = O(f(N)) and T(N) = (f(N))
(f(N)) is a tight bound, upper and lower
0.0001 N, 2100 N + log N are all = (N)
Data Structures 12
For large N and ignoring constant f
actors
T(N) = O(f(N))
means T(N) is less than or equal to f(N)
Upper bound
T(N) = (f(N))
means T(N) is greater than or equal to f(N)
Lower bound
T(N) = (f(N))
means T(N) is equal to f(N)
“Tight” bound, same growth rate
T(N) = o(f(N))
means T(N) is strictly less than f(N)
Strict upper bound: f(N) grows faster than T(N)
Data Structures 13
Big-Oh Analysis of iterative sum function
Data Structures 14
Big-Oh Analysis of recursive sum function
Data Structures 15
Common Recurrence Relations
Data Structures 16
Big-Oh Analysis of Recursive Algorithm
s
Data Structures 17
Recursion
Data Structures 18
Recursive Fibonacci Function
int fib(int N) {
if (N < 0) return 0; //invalid input
if (N == 0 || N == 1) return 1; //base cas
es
else return fib(N-1)+fib(N-2);
}
Data Structures 19
Recursive Fibonacci Analysis
int fib(int N) {
if (N < 0) return 0; // time = 1 for (N < 0)
if (N == 0 || N == 1) return 1; // time = 3
else return fib(N-1)+fib(N-2); //T(N-1)+T(N-2)+1
}
Data Structures 20
Iterative Fibonacci Function
int fib_iter(int N) {
int fib0 = 1, fib1 = 1, fibj = 1;
if (N < 0) return 0; //invalid input
for (int j = 2; j <= N; j++) { //all fib nos. up to N
fibj = fib0 + fib1;
fib0 = fib1;
fib1 = fibj;
}
return fibj;
}
Running time = ?
Data Structures 21
Iterative Fibonacci Analysis
int fib_iter(int N) {
int fib0 = 1, fib1 = 1, fibj = 1;
if (N < 0) return 0; //invalid input
for (int j = 2; j <= N; j++) { //all fib nos. up to N
fibj = fib0 + fib1;
fib0 = fib1;
fib1 = fibj;
}
return fibj;
}
Data Structures 22
Appendix
Data Structures 23
Matlab - bigo.m
% bigO functions
% calculate and plot several functions used in comparing growth rates
figure
plot(n,y1,'y','LineWidth',2)
hold on
plot(n,y2,'r','LineWidth',2)
plot(n,y3,'g','LineWidth',2)
plot(n,y4,'b','LineWidth',2)
plot(n,y5,'m','LineWidth',2)
plot(n,y6,'c','LineWidth',2)
hold off
Data Structures 24