i = 1;
while (i <= n) {
j = n - i;
while (j >= 2) {
for (k = 1; k <= j; k++) {
s = s + Arr[k];
}
j = j - 2;
}
i = i + 1;
}
The part that confuses me is where it says
j = n - i;
while(j >= 2){
I'm not really sure how to show my work on that part. I'm pretty sure the algorthim is O(n^3) though.
You can simplify it a bit in order to see things more clearly:
for(i = 1; i <= n; i++)
{
for(j = n - i; j >= 2; j -= 2)
{
for(k = 1; k <= j; k++)
{
s = s + Arr[k];
}
}
}
Now things should be simpler
for(i = 1; i <= n; i++)
: O(n) [executes exactly n times, actually] for(j = n - i; j >= 2; j -= 2)
: (n-1)/2
in 1st iteration, (n-3)/2
in the 2nd and so on... O(n) for(k = 1; k <= j; k++)
n-2
in 1st iteration, n-3
in the 2nd and so on... O(n) s = s + Arr[k];
[simple operation] : O(1) Multiply every step and you get O(n^3)
If you are still having trouble with it, I would suggest you run a few simulations of this code with varying n
values and a counter inside the loops. Hopefully you'll be able to see how the O(n)
is the complexity for each loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.