* When we write any program, 2 things are very important :
a. Time
b. Space
* The whole or a piece of a code block execution time varies based on input. And this execution time can be represented using "Big-O notation".
* The Big-O notation measures the worst-case complexity of an algorithm.
* In Big-O notation, "n" represents the number of inputs. The question asked with Big-O is the following: “What will happen as "n" approaches infinity?”
Our Logic time complexity we are going to represent using based on input (that is all about Big-O). Why not other parameters?
Below are the comparisons:
Execution times? Not a good measure as execution times are specific to a particular computer.
The number of statements executed? Not a good measure, since the number of statements varies with the programming language as well as the style of the individual programmer.
Ideal solution? Let us assume that we express the running time of a given algorithm as a function of the input size n (i.e., f(n)) and compare these different functions corresponding to running times. This kind of comparison is independent of machine time, programming style, etc.
Note: While representing Big-O notation, we will ignore constants(you can observe in the below examples). We might be asking a question ourselves, why to ignore? (below screenshot will help us to understand the same)
Examples and identifying the time complexity:
Example 1: Retrieving/accessing an element from Array or List by it's Index.
function callMe(n)
{
var arr=[2,3,4];
Console.log(arr[2]); //output: 4
}
note: This will be always 1 which means execution time is not dependent on the input.
1 2 3 4 5 6 7 8 9 10 11 12 13 | function callMe(n) { var count =0; for (var i=0;i<n;i++) { count+=1; } for (var i=0;i<5*n;i++) { count+=1; } return count; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | function callMe(n) { var count =0; for (var i=0;i<n;i++) { count+=1; for (var i=0;i<5*n;i++) { count+=1; } } return count; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function callMe(n) |
1 2 3 4 5 6 7 | function callMe(n) |
1 2 3 4 5 6 7 | function callMe(n) var count =0; for (var i=1;i<=n;i=i*2) { console.log(n+' count '+(count++)+'\n'); } } |
Note: for a value of 1 million the above will execute 19 times.
1 2 3 4 5 6 7 | function callMe(n) { while (true) { console.log(n); } } |
Comments
Post a Comment