Personal tools
You are here: Home Classes Fall 2004 - Spring 2005 CS 151 Asymptotic Analysis
Navigation
Log in


Forgot your password?
« May 2008 »
Su Mo Tu We Th Fr Sa
123
456789 10
11121314151617
18192021222324
25262728293031
 
Document Actions

Asymptotic Analysis

by admin last modified 2005-05-11 18:12

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 n0 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(n3) < ... < 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(g2(n)), then f1(n)+f2(n) is O(max(g1(n), g2(n))).


Some examples

The following program uses a selection sort to sort an array of integers:
void sort(int[] array){
    int n = array.length;

    for(pick = 0; pick<n-1; pick++){
// find the smallest element among array[pick], array[pick+1],...,array[n-1]
    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;
    } // end of for(pick) loop

}
Analyze its running time.


The following program returns the nth number in the Fibonacci sequence  1,1,2,3,5,8,13,21,....
int fibonacci(int n){
  if(n==1 || n==2)
    return 1;
  else
    return fibonacci(n-1) + fibonacci(n-2);
}
Analyze its running time.

Here's an alternative way to compute the same values:
int fibonacci(int n,int f1,int f2){
  if(n==1)
    return f1;
  else if(n==2)
    return f2;
  else
    return fibonacci(n-1,f2,f1+f2);
}
Analyze its running time.




 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: