简体   繁体   中英

Why is the bigO of this algorithm m^2*n?

I am trying to determine why the bigO of this algorithm is m^2*n, and why the innermost loop is executing in m^2*n steps.

   int m=10, n=15;
   int inLoop = 0, midLoop = 0, outLoop = 0; 

   for(int i=1;i<=m;i++)
   {
    outLoop++; 
        for(int j=1;j<=2*i-1;j++)
        {
            midLoop++; 
            for(int k=1;k<=n;k++)
            {
            inLoop++; 
            }
        }
   }

   System.out.println("Out Loop " + outLoop);
   System.out.println("Mid Loop " + midLoop);
   System.out.println("Inner Loop " + inLoop);

When I run this, I get that the inner loop runs 1500 times, the middle loop 100 times, and the outermost loop 10 times.

Before running this code I thought that this code ran the first loop m times, the second loop m^2 times, and the last loop n times, which with these values would result in the inner loop output to be 15,000.

Apparently the algorithm seems to be executing the innermost loop in m^2 * n steps as opposed to the m^3*n steps I believed it would be.

summation(2i - 1) as i starts at 1 and ends at m is:

2*summation(i) - summation(1) = 2 * (m+1)/2 * m - m = O(m^2)

This is only for the outer and middle loop

The inner loop is straight forward resulting in O(n * m^2)

I think that the idea is clear, that you count how often each loop is repeated, and that it's rather the details that are unclear. Now, in order to ease these things, you can separate these loops and conquer them separately.

For the outermost loop, it is pretty clear that it runs m times. That is, its complexity is Θ(mx), with x being the complexity of what's inside. For the innermost loop, the case is also pretty simple, it only depends on the value of n , which is constant, so its complexity is Θ(n).

The middle loop is the one that is a bit more complicated. Its complexity depends on i , but i is not constant but the loop variable of the outer loop. However, you can use the average as replacement. In this case the average is pretty simple, which you can visualize if you draw a checkboard. In the first iteration of the outer loop, i=1 , so j will only take a single value 1 . In the second iteration, i=2 and j=1..3 . In the third, it's j=1..5 and so on. If you draw these underneath each other, you get a triangle-like shape. It has the width 1 at the top, the width 2m-1 at the bottom and a height of m . It's area is therefore ((2m-1)+1)/2=m .

Putting this together, you have complexities Θ(m) for the outer and middle loop and Θ(n) for the inner loop, making it Θ(m²n) overall.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM