Computer Science, asked by teradaddy420owq3jl, 1 year ago

How to calculate time complexity in this?

Attachments:

Answers

Answered by nibod1248
0

for(int i=0;i<N;i++)

Let's calculate the time complexity for this particular loop-

assumption-> 1 unit for each comparison, initialization and arithmetic operation  

1 for initialization (i=0)

N+1 for comparison (i<N)  

N for incremental operator (i++)

So total instructions which will be executed by machine = 2*N + 2.

So In terms of Big O notation it will be O(N)

Because our constant factor won't matter much If N tends to higher values.

Suppose N is a million, then the first term(2*N) will be 2 million and other one will be 2 which is negligible.

So for this reason, we drop all but the largest terms for large N.

So now we have gone {2*N + 2} to {2*N}.

We don't really care if there is some constant multiple of difference in performance when N is large.

So we write the time complexity of this loop is O(N).

Now consider another case

for(int i=0;i<N;i*=c)  //c  is some constant

time complexity for this loop will be O(logn)

Because the iterative variable is incremented geometrically.  

another example

for(int i=0;i<N;i+=c) // c is some constant

time complexity for this loop will be O(N)  

If you are removing only few comparisons within loop then time complexity will remain same for larger N.

I hope this answer will help you to compute the time complexity of your improved algorithm.

Similar questions