简体   繁体   English

代码 Θ(nLogn) 的时间复杂度如何?

[英]How is time complexity of the code Θ(nLogn)?

 int n;
 int i, j, k = 0;
    for (i  = n/2; i <= n; i++) {
        for (j = 2; j <= n; j = j * 2) {
            k = k + n/2;
        }
    }

Just need to calculate the time complexity of the code snippet and the answer is Θ(nLogn) but can you explain how it is Θ(nLogn)只需要计算代码片段的时间复杂度,答案是 Θ(nLogn) 但你能解释一下它是如何 Θ(nLogn)

It's really not that difficult.真的没有那么难。

The outer loop runs n/2 times.外循环运行n/2次。 That is O(n) complexity.O(n)复杂度。

The inner loop again depends on n only.内部循环再次仅依赖于n It doesn't depend on the i from the first loop.它不依赖于第一个循环中的i So for the complexity of the inner loop we can ignore completely the outer loop.所以对于内循环的复杂性,我们可以完全忽略外循环。 How fortunate!.多么幸运!。 j multiples each time by 2 so we have logarithm base 2 . j每次乘以2所以我们有logarithm base 2 That is O(log(n)) .那就是O(log(n))

The loops are nested so we multiply, thus ending with:循环是嵌套的,所以我们相乘,从而以:

O(n log(n))

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

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