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)
?
fn(n) = n + 2 n log(n)
would have order 1? Clearly, O(n log n) is not in a subset of O(n). – amon Feb 28 '21 at 11:13f(n) = n+1+n = 2n+1
" from? You're correct that we'd generally describe that first loop as O(n), though there's something off about the reasoning. – Nat Feb 28 '21 at 15:38