Consider the following C-program fragment in which i, j and n are integer variables.
for (i = n, j = 0; i >0; i /= 2, j += i); |
Let val(j) denote the value stored in the variable j after termination of the for loop. Which one of the following is true?
(A) val(j) = Θ(logn)
(B) vaI(j) = Θ(sqrt(n))
(C) val(j) = Θ(n)
(D) val(j) = Θ(nlogn)
(A) val(j) = Θ(logn)
(B) vaI(j) = Θ(sqrt(n))
(C) val(j) = Θ(n)
(D) val(j) = Θ(nlogn)
Answer (C)
Note the semicolon after the for loop, so there is nothing in the body. The variable j is initially 0 and value of j is sum of values of i. i is initialized as n and is reduced to half in each iteration.
j = n/2 + n/4 + n/8 + .. + 1 = Θ(n)
No comments:
Post a Comment