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;
Big O indicates the order of the complexity of your algorithm.
Basic things :
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 asO(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)