I am trying to understand the calculation of Big-oh notation of a function, when a function contains a for-loop, which has a specific condition
for (initialization, condition, increment)
or() like below:
public void functE( int n )
{
int a;
for ( int i = 0; i < n; i++ )
for ( int j = 0; j <= n - i; j++ )
a = i;
}
I suppose the big-oh of this function to be O(n^2), is this valid?
Assuming a = i
takes 1 time unit, you can consider each i
:
So in total:
T(n) = (n+1) + (n) + (n-1) + ... + 2 = n + [1 + ... + n] = n + n * (n + 1)/2 = (n^2 + 3n) / 2 = O(n^2)