ans 1.
sum1=0;
for(k=1; k<=n; k*2).....//it executes log n + 1 times
for(j=1; j <= n; j++)....// it executes n times for each iteration.
sum1++;
------------------------------------------------------------------------------------------------------------------------
n |
k ( executes log n + 1 times) |
j (executes n times for each iteration) |
1 |
1 |
1 |
2 |
1,2 i.e. 2 times |
(1,2) , (1,2) |
4 |
1,2,4 i.e. 3 times |
(1,2,3,4) , (1,2,3,4) ,(1,2,3,4) |
8 |
1,2,4,8 i.e. 4 times |
(1,2,3,4,5,6,7,8), (1,2,3,4,5,6,7,8), (1,2,3,4,5,6,7,8), (1,2,3,4,5,6,7,8) |
... |
............................ |
...................... |
n |
logn + 1 times |
n times for each iteration |
T.C. = O(no. of times outer loop executes * no. of times inner loop executes for each outer loop iteration)
= O((log n + 1) *n)
= O(n log n)
---------------------------------------------------------------------------------------------------------------------------------------------------------
ans 2.
sum2=0;
for(k=1;k<=n;k*=2)....// it executes log n + 1 times
for(j=1; j<=k; j++)...// it executes k times.
sum2++;
n |
k ( executes log n + 1 times) |
j (executes k times for each iteration) |
1 |
1 |
1 i.e. 1 time |
2 |
1,2 i.e. 2 times |
(1 ), (1,2 ) i.e 3 times |
4 |
1,2,4 i.e. 3 times |
(1) , (1,2) , (1,2,3) i.e. 6 times |
8 |
1,2,4,8 i.e. 4 times |
(1) , (1,2) , (1,2,3) , (1,2,3,4) ... 10 times |
... |
............................ |
...................... |
n |
logn + 1 times |
(1) , (1,2) , (1,2,3) , (1,2,3,4) ... (1,2,3,4,..k)
i.e. k(k+1)/2 times
|
T.C. = O$\left ( \frac{k*(k+1)}{2} \right )$
= O$\left ( \frac{(log n + 1)*( log n + 1 +1)}{2} \right )$
= O( log n * log n )