简体   繁体   中英

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?

This loop executes n/2 times on the average:

  • On the first iteration this executes up to n-1 times, because j starts at 1
  • On the second iteration this executes up to n-2 times, because j starts at 2
  • On the third iteration this executes up to n-3 times, because j starts at 3
  • ...
  • On the last iteration this executes zero times, because i+1 is equal to the length of the array.

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; 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.

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