Question

Analyze the following code fragments and write down the Big-O estimates of the following code fragments....

Analyze the following code fragments and write down the Big-O estimates of the following code fragments. Provide a concise explanation how you got your answer.

c. for (int j = 0; j < n; j++)

{

    for (int k = 0; k < n; k++)

         cout << (j + k) << endl;

}

d. while (n > 1)

{   

k += n *3;

n = n / 2;

}

e. int temp = n;

for (int j = 0; j < n; j++)

{

while (temp > 1)  

temp = temp / 2;

}

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

c.

for (int j = 0; j < n; j++)

{

for (int k = 0; k < n; k++;

cout << (j + k) << endl;

}

Answer: O(n2)

Explanation:

1. The given method has nested for loop.

2. The inner loop executes n times and the outer loop also executes n times, Hence the total complexity isO(n2).

d.

while (n > 1)

{   

k += n *3;

n = n / 2;

}

Answer: O(n/2)

Explanation:

Complexity is considered to be the worst case implementation, Let us consider the n = 2; Then the while loop is executed 1 time;

Let the n value is 8; then the loop is executed 3 times; As the value of n increses the number times the loop execution decreases, but when compared to the worst case scenario, the maximum times the statements executed is n/2;

So the complexity is O(n/2).

e.

int temp = n;

for (int j = 0; j < n; j++)

{

while (temp > 1)  

            temp = temp / 2;

}

Answer: O(n)

Explanation:

The inner executes n/2 as explained in the part e. similarly the outer loop executes n times. So the complexity is O(n, n/2). The maximum of two is n. Therefore the complexity is O(n).

Add a comment
Know the answer?
Add Answer to:
Analyze the following code fragments and write down the Big-O estimates of the following code fragments....
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