简体   繁体   English

这个for循环的运行时间复杂度是多少

[英]What is the running time complexity of this for loop

for (int p = t; p > 0; p >>= 1) {
    for (int i = 0; i < n - p; ++i) {
        if ((i & p) != 0) {
            sort2(a, i, i+p);
        }
    }
    for(int q = t; q > p; q >>= 1) {
        for(int i = 0; i < n- q; ++i) {
            if ((i & p) != 0) {
                sort2(a, i+p, i+q);
            }
        }
    }
}

Here n is some positive integer and t is greater than n/2 , but not equal to n . 这里n是一些正整数,并且t大于n/2 ,但不等于n

As per my understanding, the inner for loop runs for (np) times but I could not figure out the outer for loop. 根据我的理解,内部for循环运行(np)次,但是我无法弄清楚外部for循环。

I tried finding it as below: 我尝试找到它,如下所示:

If t=64 and n=100 , it takes the binary value of p which is equal to 64 and so p=1000000 base 2 . 如果t=64n=100 ,则采用p的二进制值,该值等于64 ,因此p=1000000 2 p=1000000

I understand that every time it reduces by one digit and it executes a total of 7 times in this case. 我知道,每次它减少一位数,在这种情况下,它总共执行7次。 I somehow couldn't figure out general time. 我不知道怎么算一般时间。

Also, my understanding is that the 3rd for loop ie 另外,我的理解是第三个for循环

for(int q = t; q > p; q >>= 1)

doesn't execute at all because the condition q>p doesn't satisfy as p=q=t . 因为条件q>p不满足,因为p=q=t所以根本不执行。

Is this correct? 这个对吗? I am just starting out with algorithms. 我只是从算法开始。

For this: Complexity would be BigO( log(t)(nt)log(t) ) 为此:复杂度为BigO( log(t)(nt)log(t) )

Excluding the sort2 function complexity inside the for loop. 不包括for循环内的sort2函数复杂性。

Explaination: 说明:

  • Outer loop Complexity would be log(p)+1 [Each time it is right shifting the bit by 1 and going for greater than 0 ], so for t = 64, the loop will go as [64, 32, 16, 8, 4, 2, 1]. 外循环复杂度将为log(p)+1 [每次将位右移1并greater than 0 ],因此对于t = 64,循环将变为[64,32,16,8, 4,2,1]。
  • Inner loop complexity is going to be greater of ( O(np), O((nt)log(t)) ) 内循环复杂度将greater of ( O(np), O((nt)log(t)) )

Execution 执行

for the second inner loop having nested for loop with the most outer loop: 对于第二个内部循环,嵌套了for循环和最外部的循环:

在此处输入图片说明

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

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