[英]Why is the inner loop executing (n/2) times instead of (n) times
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) return true;
}
}
Edit: Forgot to add the outer loop. 编辑:忘记添加外循环。 i is initialized to zero.
我被初始化为零。
Why is this code executing (n/2) times instead of (n) times? 为什么此代码执行(n / 2)次而不是(n)次?
This loop executes n/2 times on the average: 该循环平均执行n / 2次:
If you add the first line to the last, the second to the second from the back, the third to the third from the back and so on, each pair would yield n-1; 如果将第一行添加到最后一行,第二行从后面添加到第二行,第三行从后面添加到第三行,依此类推,每对将产生n-1; there would be n/2 such pairs for even values of n, so an average number of times the loop executes over n is n/2.
对于偶数个n值,将有n / 2这样的对,因此循环在n上执行的平均次数为n / 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.