简体   繁体   English

算法运行时间分析

[英]analysis of algorithm run time

What would the big-O run time be? 大O运行时间是多少? I'm mostly confused about the while loop run time. 我对while循环运行时很困惑。 I know the run times for both for loops are O(n). 我知道for循环的运行时间都是O(n)。

cin >> n >> min >> max;

for(int i = min; i < n; i++) {

     for(int j = 1; j < max; j++) {

        total = 1;

        while(total < n) {

             total = total *2;

        }

    }
}

The progression of target in the while loop is: while循环中target的进展是:

1 2 4 8 ... 2^P

You need log(2, n) steps -- ie log of n in base 2 . 您需要log(2, n)步骤 - 即在base 2 log n That loop is O(log n) . 那个循环是O(log n)

First of all, it looks like you forgot to put braces. 首先,看起来你忘了戴上牙套。 I'm your code, as it is, the whole loop is not inside the nested for loops. 我是你的代码,因为它是整个循环不在嵌套的for循环中。 As it is, we have a pointless nested for loop that just sets total to 1, followed by an independent while loop. 实际上,我们有一个无意义的嵌套for循环,只需将total设置为1,然后是一个独立的while循环。 The complexity of the first is O((n - min) * max), and the second is O(log(n)). 第一个的复杂度是O((n - min)* max),第二个是O(log(n))。 The total time complexity is the sum of these. 总时间复杂度是这些的总和。

Probably what you really meant is this: 可能你真正的意思是:

for(int i = min; i<n; i++) {

 for(int j =1; j< max; j++) {

    total = 1;

    while(total < n) {
         total = total *2;
    }
  }
}

Here, we have the whole loop inside the nested for loops. 在这里,我们在嵌套的for循环中有整个循环。 The time complexity is the multiple of what we calculated earlier, so O((n - min) * max * log(n)). 时间复杂度是我们之前计算的倍数,因此O((n - min)* max * log(n))。 If min and max are constants, then we can reduce to O(n log n) 如果min和max是常量,那么我们可以减少到O(n log n)

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

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