Asymptotic Analysis
Asymptotic Analysis
Big-oh notation
definition Let f(n) and g(n) be functions defined for nonnegative integers. We say that f(n) is O(g(n)) if there is some integer n 0 and some constant C such that for all n > n0, f(n) <= Cg(n).example Let f(n) = 3n + 7. Show that f(n) is O(n).
example Let f(n) = 3n3 + 2n2 + n + 1. Show that f(n) is O(n3).
Big-oh notation is used to classify algorithms based on their running times.
O(1) < O(log n) < O(n) < O(n log n) < O(n2) < O(n 3) < ... < O(2n)
What are the big-oh running times for the sum and size programs we looked at earlier?
Some rules
If f(n) is O(c g(n)) for some constant c, then f(n) is O(g(n)).If f1(n) is O(g1(n)) and f2(n) is O(g 2(n)), then f1(n)+f2(n) is O(max(g 1 (n), g2(n))).
Some examples
The following program uses a selection sort to sort an array of integers:
void sort(int[] array){Analyze its running time.
int n = array.length;
for(pick = 0; pick<n-1; pick++){
// find the smallest element among array[pick], array[pick+1],...,array[n-1]} // end of for(pick) loop
imin = pick;
for(i=pick+1;i<n;i++)
if(array[i]<array[imin])
imin=i;
// swap the smallest element with the pick element
temp = array[pick];
array[pick] = array[imin];
array[imin] = temp;
}
The following program returns the nth number in the Fibonacci sequence 1,1,2,3,5,8,13,21,....
int fibonacci(int n){Analyze its running time.
if(n==1 || n==2)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
Here's an alternative way to compute the same values:
int fibonacci(int n,int f1,int f2){Analyze its running time.
if(n==1)
return f1;
else if(n==2)
return f2;
else
return fibonacci(n-1,f2,f1+f2);
}