Example: Time Complexity of an Algorithm With Nested Loops
In this lesson, we will learn how to compute the time complexity of an algorithm that involves nested for loops.
We'll cover the following...
A Program With Nested for Loops
Consider the following Java program:
Java
class NestedLoop {public static void main(String[] args) {int n = 5; // 1 stepint m = 7; // 1 stepint sum = 0; // 1 stepfor (int i = 0; i < n; i++) { // n stepsfor (int j = 0; j < m; j++) { // n*m stepssum++; // n*m steps}}System.out.println("Sum: " + sum); // 1 step}}
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.
Time Complexity
Let’s take the training wheels off and jump straight to line number 6 which accounts for ...