retagged by
1,713 views
2 votes
2 votes
Consider the following code . What should be the time complexity?
j = n  ;

while (j >= 1){    

 for (i = 1 to j    )   

   x = x + 1    ;

 j = n/2 ;

 }
 

(A)O(logn)
(B)O(n logn)
(C)O(n )
(D)None of the above
retagged by

3 Answers

Best answer
8 votes
8 votes

The only thing which you need to care is that $j = \frac{n}{2}$ this will not allow this program to terminate if $n > 1$

j = n;
while (j >= 1){
    for (i = 1 to j)
        x = x + 1;
    j = n/2;           // If n > 1 then J will always be greater than 
                       // or equal to 1, hence this loop will not terminates. 
}

Hence Answer will be D) None of the above

Thanks @manojK

selected by
0 votes
0 votes

Outer while loop will run O(log n) times

inner loop for each iteration of outer loop will run

when j=n inner loop will run n times

"       j=n/2  "     "      "    "  n/2  "

 "      j=n/4  "      "     "   "   n/4  "

.

.

.

"      j=2   "     "    "    "   1   "

inner loop will total run =1+2+4+ .......+n/4+n/2+n

                                = 1(2n -1) /(2-1) =O(2n)

reshown by
0 votes
0 votes

for (i=1 to j) => j=n => so runs n times

=>j=n/2 so runs n/2 times

=>j=n/8 so runs n/8 times

So, it runs, n+n/2+n/8+n/16+.........1

Calculating it, we get O(n) times.

Related questions

622
views
1 answers
1 votes
Sajal Mallick asked Nov 28, 2023
622 views
Consider the problem that given a set Sof n integers and another integer x, whether or not there exist two elements in S whose sum is exactly x. What is the worst ... in dynamic programming? Then complexity should be O(n^2).How O(n logn)?
220
views
0 answers
0 votes
321
views
1 answers
0 votes
NeelParekh asked Jul 27, 2023
321 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?
499
views
1 answers
2 votes
h4kr asked Dec 30, 2022
499 views
What is the correct time complexity in $\theta()$ ?