Algorithm - Analysis & Big O
Algorithm - Analysis & Big O
Analysis
Function Name
c Constant
Log N Logarithmic
Log2 N Log-squared
N Linear
N log N N log N
N2 Quadratic
N3 Cubic
Nd, d > 3 Polynomial
2N Exponential
Engr. Hammad Shahab 8
N! factorial
Engr. Hammad Shahab 9
Engr. Hammad Shahab 10
Big O Example
• 1000N > N2 for smaller values of N
• However, 1000N ≤ N2 for N ≥ 1000
T(N) ≤ c(f(N)) when N ≥ n0
c = 1, n0 = 1000
A: O(N)
Engr. Hammad Shahab 15
Example:
void count_lines(char* str, int size)
{ int i; // no complexity. It's only a declaration
int c = 0;
for (i = 0; i < size; ++i) // loop executed size times -> O(size)
if (str[i] == '\n') // array access -> O(1)
c++; // simple Variable access -> O(1)
return c; } // simple variable access -> O(1)
Running time??
O(size)