...

/

Introduction to Time Complexity

Introduction to Time Complexity

Learn the basics of time complexity and its calculation.

Time complexity calculation

We’ve learned that data structures are discrete structures. So, algorithms are all about discrete structures.

Let’s consider a simple Java program where we simultaneously iterate over two loops. These outer and inner loops are connected, and they finally give us an output.

Press + to interact
class Main {
static int i, j, totalOne, totalTwo;
public static void main(String[] args) {
for (i = 0; i <= 5; i++){
totalOne += i;
System.out.print("i = " + i);
System.out.println("--------");
for (j = 0; j <= 5; j++){
totalTwo += j;
System.out.println("j = " + j);
}
}
System.out.println("The total of the outer loop: " + totalOne);
System.out.println("The total of the inner loop: " + totalTwo);
}
}

And from this elementary program, we get the following output:

i = 0--------
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
i = 1--------
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
i = 2--------
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
i = 3--------
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
i = 4--------
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
i = 5--------
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
The total of the outer loop: 15
The total of the inner loop: 90

Time complexity of only one loop

This is a ...