简体   繁体   English

为什么内部循环执行(n / 2)次而不是(n)次

[英]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次:

  • On the first iteration this executes up to n-1 times, because j starts at 1 在第一次迭代中,它最多执行n-1次,因为j从1开始
  • On the second iteration this executes up to n-2 times, because j starts at 2 在第二次迭代中,它最多执行n-2次,因为j从2开始
  • On the third iteration this executes up to n-3 times, because j starts at 3 在第三次迭代中,它最多执行n-3次,因为j从3开始
  • ... ...
  • On the last iteration this executes zero times, because i+1 is equal to the length of the array. 在最后一次迭代中,它执行零次,因为i + 1等于数组的长度。

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.

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