My solution for the third loop is
t(n) = [ (n-1)*n + ((n-1)*n)/2 ] *D + [ n^2 +n ] *D + [ 2n ]*I
so it is in O(n^2)
given that doSomething()
has a constant time
and that i
and j
are integers.
The second term ( [ n^2 +n ] *D
) is fairly easy.
The loop
for (j = n; j < 2 * n; j ++ ) doSomething();
gets called while i <= n
so it will be called n+1
times, since it starts from 0.
The loop for (j = n; j < 2 * n; j ++ )
calls doSomething()
n
times, so we have (n+1)*n*D = [n^2+n] *D
. I assume that doSomething()
has a constant time which is equal to D
The first term is a little bit more complex.
for (j = i; j < 2 * i; j ++ ) doSomething();
gets called when i>n
so it will be called n-1
times.
The loop calls doSomething()
i times.
The first time it gets called n+1
, the second time ´n+2´ and so on until it is 2n-1
which is equal to n + (n-1)
.
So we get a sequence likes this {n+1, n+2, n+3, ... , n+(n-1)}
.
If we sum up the sequence we get n-1
times n
and the sum 1+2+3+...+ (n-1)
.
The last term can be solved with the "Gaußsche Summenformel" (sorry I don't have the English name for it but you can see the formula in the German wiki link) so it is equal to ((n-1)*n)/2
So the first term is (n-1) * n + ((n-1)*n)/2 *D
And the last term is therefor the if statement which is called 2*n*I
, where I
is the time to execute the If statement.