Search⌘ K
AI Features

Introduction to Time Complexity

Explore the concept of time complexity to understand how different algorithms perform in programming. Discover how iteration and recursion affect the efficiency of solving problems, and learn to choose the best algorithm based on its time complexity rather than execution time.

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.

Java
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 simple algorithm for finding the total of the inner and ...