Linear time

Let's now discuss one of the most common time complexities, the linear time. As one can guess, linear time complexity of a method indicates that the method takes linear time to execute: 

for(var i = 0; i < N; i += c) {
// O(1) operations
}

This is a very basic for loop, within which we are performing some constant time operations. As the size of N increases, the number of the times the loop gets executed also increases.

As you can see, the value of i in each iteration is incremented by a constant, cand not by 1. This is because it does not matter what the increments are, as long as they are linear.

In the first iteration, the value of i = 0; in the second iteration, the value of i = c, then its c + c = 2c in the third iteration, and 3c in the fourth iteration, and so on. So, in the nth iteration, we have the value of i = c(n-1), which asymptotically is O(n).

Depending on what your use case is, linear time complexity may, or may not, be good. This is kind of the gray area, which you may sometimes want to let go if you are unsure of whether further optimization is necessary or not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.203.144