Is this O(N^2) or O(nlogn). Isnt it n^2 when there are nested loops?
int a[], N;
int f1(){ int i, j, sum=0;
for (i=1;; i=2*i)
{
If (i>=N) return sum;
for (j=1; j<2*i;j++) sum+=a[i];
}
This is O(N log N)
as the outer loop is doubling the value of i
in every iteration. So the complexity of outer loop is O(log N)
instead of O(N)
.
If you had i++
or similar instead of i=2*i
then the time complexity of two loops would have been O(n^2)
.
Edit: this is a simplified analysis. Please see the answer from R Sahu for more rigorous analysis.
Is this O(N^2) or O(nlogn).
It is neither.
Isnt it n^2 when there are nested loops?
That is true when you iterate over the items linearly. That is not true in your case.
In your case ...
The values of i
are: 1 2 4 8 16 ... N
The inner loop is executed 2 + 4 + 8 + 16 + 32 ... N times.
That is a geometric series. The sum of a geometric series is a(1 - r^n)/(1 - r)
.
In your case, a
is 2
, r
is 2
, and n
is log2(N)
(log with base 2). Hence, the sum, after some simplification, is 2*2^(log2(N))
, which is same as 2*N
.
ie your algorithmic complexity is O(N)
.
Thanks are due to @LedHead for correcting the error in the initial post.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.