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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With