Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complexity of code

Tags:

java

c

algorithm

what is the complexity of a program having only one loop, is it log n? can someone give me some ideas about estimating complexity of codes?

like image 768
javaLearner Avatar asked Sep 16 '26 17:09

javaLearner


2 Answers

Well, that really depends on what is going on in that loop.

This loop is linear time, i.e., O(n):

int sum = 0;
foreach( int i in SomeCollection )
{
    sum += i;
}

However, consider a loop which performs a substring search during each iteration. Now you have to consider the complexity of the string searching algorithm. Your question can't be answered as it stands. You will need to provide a code sample if you want a meaningful answer.

like image 117
Ed S. Avatar answered Sep 19 '26 05:09

Ed S.


Software Complexity

There is a field of study that attempts to quantify exactly that.

It's called cyclomatic complexity.

In this case, I believe your complexity rating would be p = 2, because the loop is conditional and that means there are two paths through the method.

Time complexity

If you are referring to time complexity, it's still just O(1) unless the loop iteration count is derived via a polynomial or exponential function, perhaps indirectly because the method is itself called in a higher loop, or because the loop counter is effectively multiplied by string operations or something at a lower level.

like image 43
DigitalRoss Avatar answered Sep 19 '26 05:09

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!