简体   繁体   中英

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 .

As per my understanding, the inner for loop runs for (np) times but I could not figure out the outer for loop.

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 .

I understand that every time it reduces by one digit and it executes a total of 7 times in this case. I somehow couldn't figure out general time.

Also, my understanding is that the 3rd for loop ie

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 .

Is this correct? I am just starting out with algorithms.

For this: Complexity would be BigO( log(t)(nt)log(t) )

Excluding the sort2 function complexity inside the for loop.

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].
  • Inner loop complexity is going to be greater of ( O(np), O((nt)log(t)) )

Execution

for the second inner loop having nested for loop with the most outer loop:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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