Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity n^2

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];
    }
like image 493
Nedko Avatar asked Dec 08 '25 09:12

Nedko


1 Answers

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.

like image 169
taskinoor Avatar answered Dec 10 '25 23:12

taskinoor