For the following code:
int func(int x, int y)
{
int flag=0;
for(flag=0; flag<x; flag++)
{
....
}
for(flag=0; flag<y; flag++)
{
....
}
return 0;
}
for the following cases the time complexity (my understanding) is –
x > y => O(x+y)
y < x => O(x+y)
x = y => O(2x)
Can someone verify if I am right?
Thanks.
x > y => O(x+y) — yes. But if, x = O(y), then just O(x).
y < x => O(x+y) — yes. Same explanation above.
x = y => O(2x) — not quite. You ignore the constant factor in Big O analysis. The idea is that when x goes to infinity, the ‘2’ or the constant would contribute that much towards the rate of increase of the function.
x = y^2 => O(y^2) — Another characteristic of Big O analysis is that you only consider the major term.
An excellent introduction to Big O analysis can be found here an video lecture format. Check out the second lecture for Big O analysis.