Question

For the following code, figure out the recurrences (base case and recursive step), calculate the running time and establish t

0 0
Add a comment Improve this question Transcribed image text
Answer #1

mystery(n):
if n == 1 then
   println("A");
else
   mystery(n/2);
   println("B");
   mystery(n/2);
end if


ans)

base case:
if n == 1 then
   println("A");

recursive case :
else
   mystery(n/2);
   println("B");
   mystery(n/2);


computing time complexity:
   Recurrence relation of the above recursive function : T(n) = 2T(n/2) + 1, T(1) = 1


T(n) = 2T(n/2) + 1 ---- 1
T(n/2) = 2T(n/2^2) + 1 ---- 2

substitue 2 in 1

T(n) = 2^2T(n/2^2) + 2^1 + 2^0 ---- 3
T(n/2^2) = 2 T(n/2^3) + 1 ----- 4

substitue 4 in 3

T(n) = 2^3 T(n/2^3) + 2^2 + 2^1 + 2^0
.
.
.
.
T(n) = 2^k T(n/2^k) + (2^0 + 2^1 + 2^2 + .... + 2^(k-1))

assume 2^k = n ==> k = log n

So T(n) = 2^k T(1) + (2^0 + 2^1 + 2^2 + .... + 2^(k-1))
= 2^k + (2^0 + 2^1 + 2^2 + .... + 2^(k-1))
= n + (2^k - 1)
= n + n - 1
= 2n
T(n)= O(n)
  

Add a comment
Know the answer?
Add Answer to:
For the following code, figure out the recurrences (base case and recursive step), calculate the running...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT