Example: Measuring Time Complexity—Nested Loop
Learn to compute time complexity of a given algorithm that involves nested loops.
We'll cover the following...
A nested loop
We will extend the previous example and make it a little harder by adding a “nested loop” in the program. We will calculate its time complexity by following the same series of steps that we did in the previous example. Let’s take a look at the following example. It is a simple piece of code that prints the number of times the increment statement runs throughout the program. Let’s compute its time complexity.
Running time complexity
We will first break this program into individual operations like this:
Statement | Number of Executions |
| |
| |
| |
| |
| |
| |
... | |
| |
| |
| |
| |
| |
... | |
| |
| |
| |
Total |
We’re multiplying every statement of the inner loop with because the outer loop runs it times
Also, note that while
forexecutes only once, its execution cost is , i.e., each call toforresults innindividual operations.
...