Algorithms | Analysis of Algorithms | Question 1
What is time complexity of fun()?
C
int fun( int n)
{
int count = 0;
for ( int i = n; i > 0; i /= 2)
for ( int j = 0; j < i; j++)
count += 1;
return count;
}
|
(A)
O(n2)
(B)
O(n*log(n))
(C)
O(n)
(D)
O(n*log(n*Log(n)))
Answer: (B)
Explanation:
For an input integer n,
the outermost loop of fun() is executed log(n) times
the innermost statement of fun() is executed following times. n + n/2 + n/4 + … 1
So time complexity T(n) can be written as T(n) = O(log(n)) * O(n + n/2 + n/4 + … 1) = O(n * log(n))
The value of count is also n + n/2 + n/4 + .. + 1
Quiz of this Question
Please comment below if you find anything wrong in the above post
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...