Misunderstanding small details w/ nested for-loop time complexity analysis... How to tell O(n) and O(n²) apart
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).