Suppose we have a code:
for(int i=0;i<n;i++) sum+=i;
We say the time function here is: f(n) = n+1+n = 2n+1
. The order of the time function is 1. So, our time complexity becomes O(n)
.
But, for the following code:
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j*=2)
{
statement;
}
}
For this code our time function f(n) = n + n log(n) + n log(n) = 2n log(n) +n
. But here also the order of the time function is 1. So, why we say the time complexity of this function O(nlogn)
instead of O(n)
?