I have being given the following question and can’t decide the right answer:
for (int i=1; i<=n/2; i++)
for(int j=i; j<=n-i;j++)
for(int k=i;k<=j;k++)
x++;
What’s the order of growth of the x as a function of n?
- Ω(n^3).
- Θ(n^2.5)
- Θ(n^2)
- Ο(nlogn)
- none of the above
I managed to figure out that:
T(n) = n*(n-1) + T(n-2)
but this doesn’t really help me figure out the order of growth.
maybe there is a better way of finding it?
This looks like a homework problem so I will just give you hints.
1) Suppose you just have the inner loop. How many times do you go through the inner loop, as a function of i and j? How many operations are performed every iteration of the loop? How many operations should be performed total?
2) Now suppose you just have the inner two loops. How many times do you go through the outer loop, as a function of i and n? How many times do you go through the inner loop every time you go through the outer loop? (hint: this should be different depending on what j is) How many operations should be performed total?
3) Now you are ready to look at the entire problem. How many times do you go through the inner two loops (as a function of n), and how many operations should be performed on each iteration? How many operations are performed total? (That’s your answer)
Okay, you say this isn’t a homework problem, and actually it’s harder than I thought it was, so I’ll just give you the answer.
Each inner loop runs in time j – i.
The second loop runs in time (i – i) + (i + 1 – i) + … + (i + n – 2i – i) = 1 + 2 + … + (n – 2i) = (n – 2i)(n – 2i + 1)/2, by mathematical induction.
When calculating order of growth, the 1 term is very small compared to the n, so the outer loop runs in approximately n^2/2 + (n-2)^2/2 + (n-4)^2/2 + … + 1/2.
This is approximately one fourth of 1^2 + 2^2 + … + n^2, which by induction is n(n+1)(2n+1)/6. Therefore the order of growth is Omega(n^3).