[英]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
. 当
i=0
时,内循环对j
执行n
次迭代。 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. 但是,对于
i=0,1..n-1
每个值, j
将只执行一次迭代,因为if语句将计算为true并结束内部循环。
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? 由于外循环将执行
n
次迭代,无论如何,并且由于内部循环在i=0
(非常第一次迭代)时执行n
次迭代,为什么大时间复杂度不是O(n²)而是, O(n)如果循环嵌套并且在第一次迭代中都执行n
次迭代?
You have a line that says if (j < i) j = j + n;
你有一条线说
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. 它基本上脱离了循环(当
j < i
),并且由于内循环从0开始,这将在每次第一次迭代时触发(第一次除外),使其在恒定时间内运行。
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). 这清楚地说明了为什么它是O(n)。
You could just print the values of i
and j
from the inner loop: 你可以从内循环打印
i
和j
的值:
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. 你正确地注意到只有
i=0
内循环才会迭代n
次。 For i>0
inner loop runs once only. 对于
i>0
内部循环仅运行一次。 We can sum all these iterations: i 0 +i 1 +...+ n-1 , where i 0 =n
, and for other indexes i x =1
. 我们可以求和所有这些迭代:i 0 + i 1 + ... + n-1 ,其中i 0
=n
,对于其他索引i x =1
。 So, sum of inner iterations will be n + n - 1 => 2n - 1
. 因此,内部迭代的总和将是
n + n - 1 => 2n - 1
。 Which gives us: O(2n - 1) => O(2n) - O(1) => 2*O(n) - O(1) => O(n)
. 这给出了我们:
O(2n - 1) => O(2n) - O(1) => 2*O(n) - O(1) => O(n)
。
For every n outer iteration, there are n inner iterations. 对于每n次外迭代,都有n次内迭代。 So you will do n*n=n^2 computations and hence the complexity is O(n^2).
因此,您将进行n * n = n ^ 2次计算,因此复杂度为O(n ^ 2)。 Does this make sense or it is more confusing?
这有意义还是更令人困惑?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.