简体   繁体   English

以Big-O表示法查找效率

[英]Find the efficiency in Big-O notation

I was having problem with the following question 我对以下问题有疑问

Consider the following nested loop construct. 考虑以下嵌套循环构造。 Categorize its efficiency in terms of the variable n using "big-o" notation. 使用“ big-o”表示法根据变量n对其效率进行分类。 Suppose the statements represented by the ellipsis (...) require four main memory accesses (each requiring one microsecond) and two disk file accesses (each requiring one millisecond). 假设用省略号(...)表示的语句需要四个主内存访问(每个都需要一微秒)和两个磁盘文件访问(每个都需要一毫秒)。 Express in milliseconds the amount of time this construct would require to execute if n were 1000. 如果n为1000,则以毫秒表示此构造执行所需的时间。

x = 1;
do
{
    y = n;
    while (y > 0)
    {
    ...
        y--;
    }
    x *= 2;
} while (x < n*n);

Inner loop with y is O(n). y的内环为O(n)。

Outer loop runs with x = 1, 2, 2^2, 2^3, ... 2^k < n * n. 外循环以x = 1,2,2 ^ 2,2 ^ 3,... 2 ^ k <n * n运行。 Hence it runs in O(log(n*n)) which is O(2 * log(n)) 因此,它在O(log(n * n))中运行,即O(2 * log(n))

Hence complexity is O(n * log(n)) 因此复杂度为O(n * log(n))

Just to add some more explanation to theother answer, a notable part of code is the x *= 2; 只是为了给其他答案增加一些解释,代码的一个显着部分是x * = 2; ie a doubling. 即加倍。 So this part is not linear. 所以这部分不是线性的。 So you should be thinking log2. 因此,您应该考虑使用log2。

Therefore, x will reach n*n in log2(n*n). 因此,x将在log2(n * n)中达到n * n。 = log2(n^2) = 2 x log2(n). = log2(n ^ 2)= 2 x log2(n)。

The y countdown is linear - so that is O(n) y倒数是线性的-因此为O(n)

There is a loop within a loop so you multiply both operations as in: 循环中有一个循环,因此您可以将两个操作相乘,如下所示:

n * 2 x log2(n) = O(n * 2 * log2(n)). n * 2 x log2(n)= O(n * 2 * log2(n))。 Then you take out constant factors to get: O(n * log2(n)) 然后,取出常数因子以获得:O(n * log2(n))

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

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