简体   繁体   English

O(N)与O(NlogN)

[英]O(N) vs O(NlogN)

I came accros this example while working on Big-O notation 我在处理Big-O表示法时使用了这个示例

x=n
while(x>0)
{
    y=x
    while(y>0)
    {   
        y=y-1
    }
    x = x/2
}

Could, you explain me why it seems to have a O(N) complexity ? 您能否解释一下为什么它似乎具有O(N)的复杂性?

This is new for me but I would expect it to be N LogN. 这对我来说是新的,但我希望它是N LogN。

What am I missing ? 我想念什么?

Thanks, 谢谢,

EDIT: this piece of code comes from here https://www.quora.com/How-can-we-check-for-the-complexity-log-n-and-n-log-n-for-an-algorithm?encoded_access_token=1b7e0a4d10f84d50b5fea810f5a89cea 编辑:这段代码来自这里https://www.quora.com/How-can-we-check-for-the-complexity-log-n-and-n-log-n-for-an-algorithm ?encoded_access_token = 1b7e0a4d10f84d50b5fea810f5a89cea

Well, let's look how often the inner loop's body is executed: 好,让我们看看内部循环的主体执行的频率:

x =   n:      n
x = n /  2: n /  2
x = n /  4: n /  4
x = n /  8: n /  8
x = n / 16: n / 16
x = n / 32: n / 32
x = n / 64: n / 64
until x < 1

Or put it together: 或放在一起:

n + n / 2 + n / 4 + n / 8 + n / 16 + n / 32 + n / 64 ...

Which is easily seen is the same as: 显而易见的是:

n + n - n / 64

Now we want an upper bound, so we may ignore the last term. 现在我们需要一个上限,因此我们可以忽略最后一项。 And for big-oh, the constant is also insignificant. 对于大哦,常数也无关紧要。 So: 所以:

O(n)

If you find how many times the inner loop runs, you find the complexity of the code. 如果您发现内部循环运行了多少次,就会发现代码的复杂性。 The inner loop runs n + n/2 + n/4 + ... n/k (where n/k>0) times. 内部循环运行n + n / 2 + n / 4 + ... n / k(其中n / k> 0)次。 The maximum value of n/2 + n/4 + ... + n/k part is n-1. n / 2 + n / 4 + ... + n / k部分的最大值为n-1。 Thus, the code can not run more than 2n-1 times making the upper bound 2n-1 which is O(n) 因此,代码的运行时间不能超过2n-1次,使上限2n-1为O(n)

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

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