Figuratively speaking, of course. I’m against animal cruelty. However, in this article we will explore other ways to compute algorithmic complexity. In a previous post, we computed the running time of the code below:

for(int i=0;i<10;i++){
for(int j=0;j<i;j++){
for(int k=0;k<j;k++){
System.out.println("Hello World");
}
}
}

Now that we learned about the Big Oh, we don’t need to know exactly how many times the “Hello World” will execute. We just need to determine the asymptotic behavior of the algorithm. To do this, we will now compute the running time of the above code snippet using elementary calculus.

In the previous post, we came up with an expression of the running time of the code snippet as

We know that the second term above is just

Also, our derivation of the sum of the first term was quite involved so we will try to avoid that as much as possible. If you take a look at the figure below, you can see the graph of . I have to mention that this figure was created using OmniGraphSketcher for Ipad.

You can also see rectangles shaded in blue. These rectangles are of width 1 unit and the height of each rectangle is the number above it. Therefore, the area of each rectangle is numerically equal to the height. As you can see from the figure, the total area of the rectangles from 1 to 4 is equal to . You can also observe that this area is less than the area under the curve, the area indicated in gray. The area under the curve is equal to the proper integral of evaluated from to , or symbolically as

You might want to ask yourself why the upper limit of integration is and not .

As can be seen clearly in the figure, the total area of the rectangles is less than the area under the curve, or

for some finite number .

Performing the integration and substituting the limits, we get

Combining this result with above, we get

By taking , we have

Therefore, the asymptotic complexity of the code snippet is .

### Like this:

Like Loading...

*Related*