Consider the following code snippet. It accepts a positive integer n as input. int i = 0. j = 0, val = 1; for (i = 1; i <= n; i++) { j = n; if (i% 2 == 0) { while (j > 1) { val = val * j; j = j /2; } } } What is the worst-case time complexity of the algorithm?
Consider the following code snippet. It accepts a positive integer n as input. int i = 0. j = 0, val = 1; for (i = 1; i <= n; i++) { j = n; if (i% 2 == 0) { while (j > 1) { val = val * j; j = j /2; } } } What is the worst-case time complexity of the algorithm? Correct Answer O(n log n)
The correct answer is option 2.
Concept:
The worst-case time complexity indicates the longest running time performed by an algorithm given any input of size n, and thus guarantees that the algorithm will finish in the indicated period of time.
Program:
int i = 0. j = 0, val = 1;
for (i = 1; i <= n; i++) // Loop one
{
j = n;
if (i% 2 == 0)
{
while (j > 1) { // Loop two.
val = val * j;
j = j /2;
}
}
}
Loop one runs n times (i=1 to i=n) So it takes O(n) time for "i" value Loop two runs.
Loop two runs like initially J=n, n/2, n/4, n/8, n/16, ...
when Loop two condition becomes n/2k< 1 then stop the Loop two.
2k = n
take to log on both sides.
k= log n
So Loop two runs O(log n) times.
For each, I value o(log n) times run the program. So for all n value takes n log n time.
Hence the correct answer is O(n log n).