1. The complexity of the merge sort is T(n) = 2T (n/2)+n.
Explain how the above equation is
derived? [Multiple Ministry-AP-2023]
Solution: T(n) = 2T (n/2) + n ------ (1)
T(n/2) = 2T(n/4) + n/2 ------ (2) [when, n= n/2]
T(n/4) = 2T(n/8) + n/4 ------ (3) [when, n= n/4]
From equation (1)
T(n)= 2[2T(n/4) + n/2] + n [Putting the value of T(n/2)]
= 22 T(n/22) + n+ n
= 22 T(n/22) + 2n
= 22[2T(n/8) + n/4 ] + 2n [Putting the value of T(n/4)]
= 23T(n/23) + n + 2n
=23T(n/23) + 3n
Similarly,
T(n) =24T(n/24) + 4n
Again, T(n) = 2k T(n/2k) + kn
When, T(n) =1, if n=1
So, n/2k = 1
n = 2k
log n = log 2k
log n = k log 2
k = log2 n
= 2k T(1) + kn
= n.1 + n log2(n)
= n + n log2(n)
Of these two terms, the domination or big term is n log2(n).
So we can write the complexity of the merge sort is T(n)= O(n log2(n)).
2. What is complexity? Find the complexity of the following code segment with justification. [NPCBL-
2023]
int f1 (int n)
{
s = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < i*i; ++j)
{
s = s + j;
}
}
return s;
}
Solution: The answer is Θ(n³).
3. Write the recursive function of the below problem and find the recurrance relation of the
function. [Milk Vita-2023]
F(n) = 1+2+3+......+(n-1)+n
Solution: The function F(n) represents the sum of integers from 1 to n, and it can be defined
recursively as follows:
Void F( int n)
{
if(n>0)
{
for(i=0; i<n; i++)
{printf(“%d”, n);
}
F(n-1);
}
Now, let's find the recurrence relation for this recursive function:
Void F( int n) T(n)
{
if(n>0) 1
{
for(i=0; i<n; i++) (n+1)
{printf(“%d”, n); N
}
F(n-1); T(n-1)
}
T(n) = T(n-1) + 2(n+1)
= T(n-1) +n