简体   繁体   English

找出大O时间的复杂性

[英]Finding the Big O time complexity

i = 1;     
while (i <= n) {
     j = n - i;
     while (j >= 2) {
         for (k = 1; k <= j; k++) {
             s = s + Arr[k];
         }
         j = j - 2;
     }
     i = i + 1;
}

The part that confuses me is where it says 让我困惑的部分是它所说的地方

j = n - i;
while(j >= 2){

I'm not really sure how to show my work on that part. 我不太确定该如何展示我的作品。 I'm pretty sure the algorthim is O(n^3) though. 我很确定算法虽然是O(n ^ 3)。

You can simplify it a bit in order to see things more clearly: 您可以稍微简化一下,以便更清楚地看到内容:

for(i = 1; i <= n; i++)
{
    for(j = n - i; j >= 2; j -= 2)
    {
        for(k = 1; k <= j; k++)
        {
            s = s + Arr[k];
        }
    }
}

Now things should be simpler 现在事情应该更简单

  • for(i = 1; i <= n; i++) : O(n) [executes exactly n times, actually] for(i = 1; i <= n; i++)O(n) [实际上执行了n次]
  • for(j = n - i; j >= 2; j -= 2) : (n-1)/2 in 1st iteration, (n-3)/2 in the 2nd and so on... O(n) for(j = n - i; j >= 2; j -= 2) :( (n-1)/2在第一次迭代中, (n-3)/2在第二次迭代中,依此类推... O(n)
  • for(k = 1; k <= j; k++) n-2 in 1st iteration, n-3 in the 2nd and so on... O(n) for(k = 1; k <= j; k++)在第1次迭代中为n-2在第n-2次迭代中为n-3 ,依此类推... O(n)
  • s = s + Arr[k]; [simple operation] : O(1) [简单操作]: O(1)

Multiply every step and you get O(n^3) 乘以每一步,您将得到O(n ^ 3)

If you are still having trouble with it, I would suggest you run a few simulations of this code with varying n values and a counter inside the loops. 如果您仍然遇到问题,建议您使用循环内的n值和一个计数器运行此代码的一些模拟。 Hopefully you'll be able to see how the O(n) is the complexity for each loop 希望您能够看到O(n)是每个循环的复杂度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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