edited by
1,944 views
1 votes
1 votes

What is the complexity of the following code?
 

i = n
while (i>=1){
    for j = 1 to n
        x=x +1
    i = i/2
}
  1. $\Theta(n)$
  2. $\Theta( \log_2 n)$
  3. $\Theta( n/\log_2 n)$
  4. $\Theta( n \log_2 n)$
edited by

2 Answers

Best answer
6 votes
6 votes
The outer while loop runs logn times because every time n is getting divided by 2 ie {n/2 , n/4 , n/8 , ......1 }

For every iteration of outer loop inner loop runs n times .

Therefore the complexity is $\Theta$(nlogn)

Ans : Option D.
selected by
0 votes
0 votes

Both the loops are independent of each other .

Inner loop always runs for n times and outer loop log₂n times . 

Hence complexity is : O(n logn)

Related questions

0 votes
0 votes
0 answers
2
0 votes
0 votes
1 answer
3
NeelParekh asked Jul 27, 2023
276 views
If an array is split in the form of increasing and decreasing order then what is TC to find minimum element in the array?
2 votes
2 votes
1 answer
4
h4kr asked Dec 30, 2022
465 views
What is the correct time complexity in $\theta()$ ?