I know time complexity for nested loop of n is O(n^2). But If I have the nested loop of as below,
for(i=0;i<n/2;i++)
for(j=0;j<n/2;j++)
...
...
How to calculate time complexity for this code. Is it also O(n^2)? If it is, how?
I know time complexity for nested loop of n is O(n^2). But If I have the nested loop of as below,
for(i=0;i<n/2;i++)
for(j=0;j<n/2;j++)
...
...
How to calculate time complexity for this code. Is it also O(n^2)? If it is, how?
Is it also O(n^2)? If it is, how?
Yes, it is.
All you have to do is count the total number of iterations (which is n/2 * n/2 = n^2 / 4
by the product rule), and bear in mind that Big-O notation ignores constants. Asymptotic analysis drops constants because they don't matter when n
tends to infinity. In other words, f(n) = n
and g(n) = 2n
are both linear functions, despite the fact that g
grows faster than f
. Asymptotic analysis only cares about classes of growth rates.
See also: