简体   繁体   中英

Misunderstanding small details w/ nested for-loop time complexity analysis… How to tell O(n) and O(n²) apart

For the algorithm below:

 int x = 0;
 for (int i = 0; i < n; i++)
     for (j = 0; j < n; j++) {
         if (j < i) j = j + n;
         else x = x + 1;
      }

So for this algorithm, my thought process goes like this:

The inner-loop performs n iterations for j when i=0 . However, for every value of i=0,1..n-1 , j will only perform one iteration because the if-statement will evaluate to true and end the inner-loop.

Here is my source of confusion:

Since the outer-loop will perform n iterations no matter what, and since the inner loop performs n iterations when i=0 (very first iteration), how come the big-Oh time complexity isn't O(n²) and is instead, O(n) if the loops are nested and both perform n iterations in the very first iteration?

You have a line that says if (j < i) j = j + n; which essentially breaks out of the loop (when j < i ), and since the inner loop starts at 0, this will trigger on the first iteration every time (except the first time), making it run in constant time.

You essentially only have one loop here. The code can be rewritten as

int x = 0;
for (int i = 0; i < n; i++) {
    x = x + 1;
}

which makes it clear why it is O(n).

You could just print the values of i and j from the inner loop:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        System.out.print(i + "" + j + " ");
        if (j < i) j = j + n;
        else x = x + 1;
    }
    System.out.println();
}

Output:

00 01 02 03 04 ..
10
20
30
40
..

Which represents only the first row and the first column of the matrix, thus the complexity is:

O(2n) => O(n).

You properly notice that only for i=0 inner loop will iterate n times. For i>0 inner loop runs once only. We can sum all these iterations: i 0 +i 1 +...+ n-1 , where i 0 =n , and for other indexes i x =1 . So, sum of inner iterations will be n + n - 1 => 2n - 1 . Which gives us: O(2n - 1) => O(2n) - O(1) => 2*O(n) - O(1) => O(n) .

For every n outer iteration, there are n inner iterations. So you will do n*n=n^2 computations and hence the complexity is O(n^2). Does this make sense or it is more confusing?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM