Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining Big O Notation

I need help understanding/doing Big O Notation. I understand the purpose of it, I just don't know how to "determine the complexity given a piece of code".

Determine the Big O notation for each of the following

a.

n=6;
cout<<n<<endl;

b.

n=16;
for (i=0; i<n; i++)
    cout<<i<<endl;

c.

i=6;
n=23;
while (i<n) {
    cout<<i-6<<endl;
    i++;
}

d.

int a[ ] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
n=10;
for (i=0; i<n; i++)
    a[i]=a[i]*2;
for (i=9; i>=0; i--)
    cout<<a[i]<<endl;

e.

sum=0;
n=6;
k=pow(2,n);
for (i=0;i<k;i++)
    sum=sum+k;
like image 238
user1074051 Avatar asked Nov 30 '11 19:11

user1074051


2 Answers

Big O indicates the order of the complexity of your algorithm.

Basic things :

  • This complexity is measured regarding to the entry size
  • You choose a unit operation (usually affectation or comparison)
  • You count how much time this operation is called
  • A constant term or constant factor is usually ignored when using complexity so if the number of operation is 3*n^3 + 12 it's simplified to n^3 also marked O(n^3)

a.) Will just run once, no loop, complexity is trivial here O(1)

b.) Call n times in the loop: O(n)

c.) Here we choose to analyze n (because it's usually the incrementing variable in an algorithm). The number of calls is n - 6 so this is O(n).

d.) Let's suppose here that 10 (n) is the size of your array and nine (i) this size minus one. For each value to n, we have to go from 0 to n then n-1 to 0. n * (n-1) operations, technically: O(n * 2) which some people approximate as O(n). Both are called Linear Time, what is different is the slope of the line which BigO doesn't care about.

e.) The loop goes from 0 to the pow(2, n), which is 1 to 2^n, summarized as O(2^n)

like image 83
AsTeR Avatar answered Sep 20 '22 23:09

AsTeR


Assuming you don't count the cout as part of your Big-O measurement.

a) O(1) you can perform the integer assignment in constant time.
b) O(n) because it takes n operations for the loop.
c) O(n - c) = O(n) constants disappear in Big-O.
d.1) O(2*n) = O(n) two linear time algorithms end up being linear time.
d.2) If n grows with pow(2, n) = 2^n, then the number of operations are O(2^n); however if n is constant it would grow with O(k), where k = 2^6 = 64, which would be linear.

like image 44
mevatron Avatar answered Sep 17 '22 23:09

mevatron