简体   繁体   English

迭代算法的时间复杂度?

[英]Time complexity of the iterative algorithm?

This is the algorithm: I think its time complexity is O(nlogn) but i am not sure 这是算法:我认为其时间复杂度为O(nlogn),但我不确定

k=1;
while (k<=n) do      
    j=1;
    while (j<=k) do        
        sum=sum+1;
        j=j+1;
    k=k*2;

The inner loop at the first time performs 1 iteration, at the second 2 iterations. 第一次的内部循环执行一次迭代,第二次执行两次。 The sequence goes like 1, 2, 4, 8, 16, 32, ... as long as it is smaller than or equal to n . 只要序列小于或等于n ,该序列就类似于1,2,4,4,8,16,32,...。 The sequence may have Θ(log(n)) elements but its sum is Θ(n) . 该序列可以具有Θ(log(n))元素,但其总和为Θ(n) This is because 这是因为

1 + 2 + 4 + ... + 2^k = 2 * 2^k - 1 1 + 2 + 4 + ... + 2 ^ k = 2 * 2 ^ k-1

and we know n/2 < 2^k <= n . 我们知道n/2 < 2^k <= n So the inner loop is performed Θ(n) times and each inner loop execution requires constant number of instructions. 因此,内部循环执行了Θ(n)次,每次内部循环执行都需要恒定数量的指令。

The rest of the code is just log(n) assignments to j = 1 and log(n) doubles of k . 的代码的其余部分只是log(n)分配给j = 1log(n)的一倍k

So the time complexity of the algorithm is Θ(n) . 因此,该算法的时间复杂度为Θ(n)

// code                 | max times executed
k=1;                    | 1
while (k<=n) do         | log n
    j=1;                | log n
    while (j<=k) do     | log n * n
        sum=sum+1;      | log n * n
        j=j+1;          | log n * n
    k=k*2;              | log n

So the O complexity would seem to be n log n. 因此,O复杂度似乎为n log n。

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

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