简体   繁体   中英

O(n) and time complexity function of the given code

if the following loop structure is under Analysis of Upper bound. Does it still Computes to O(n^2)? I'm confused since inner loop has a dependency on the outer loop and with each outer iteration inner for loop loops one less time. In addition to whatever O(n) is does the time complexity function will be "n!.n+C" Where C is a Constant? I'm assuming n! because of inner Loop.

for(int i=n;i>0;i--)
{
 for(int j=i;j>=1;j--)
  {
     count++;
  }
}

This code has the same time complexity as the code in the question.

for(int i = 0; i < n; i++){  // outer loop
    for(int j = 0; j < i; j++){  // inner loop
        count++;
    }
}

In the first iteration of the outer loop (i = 0), the inner loop doesn't execute.

In the second iteration of the outer loop (i = 1), the inner loop executes once .

In the third iteration of the outer loop (i = 2), the inner loop executes twice .

So, in the last iteration of the outer loop (i = n), the inner loop executes n times .

Therefore, the total number of times this code executes is

1 + 2 + 3 + … + n

= n(n + 1) / 2

= ((n^2) + n) / 2

= O(n^2)

lets assume, the outer loop goes to n and the inner loop goes to the value of the inner loop. (reversal case of your loop). the complete count inner cycles you can calculate with the formula

Sum k=1..n (k) = n * (n+1) / 2 = 1/2 * n^2 + 1/2 n

so you have a time complexity of

O(1/2 * n^2 + 1/2 n) = O(n² + n) = O(n²)

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