2

Sorry if this is a stupid question, but...

The order of Complexity of this code is O(n):

char buf[] = "hello world";
size_t length = strlen(buf);

for(size_t i = 0; i < length; i++)
{
    //do stuff
}

and this code is O(n^2):

char buf[] = "hello world";
for(size_t i = 0; i < strlen(buf); i++)
{
    //do stuff
}

because strlen is O(n).

But who says that strlen is O(n), is it defined in the standard, does it have to be O(n)?

How can I know for sure what the Order of Complexity of any standard function is going to be?

Bagpuss
  • 43
  • 6

3 Answers3

6

Yes, it has to be at least O(n) by design - it receives the address of the first character and has to find the null character by scanning along the string and it can only do so by advancing and checking each character.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
1

Some functions have their complexity defined in the standard. Others, included those inherited from C, don't. For those, you can't rely on anything else than quality of implementation to keep it at the minimum.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
  • doesn't that mean that the order of complexity of any code using a function with an unknown order of complexiy, is itself unknowable? – Bagpuss Mar 11 '11 at 10:54
  • 1
    @Bagpuss: Yes, any code is a black box unless specified otherwise. – sharptooth Mar 11 '11 at 10:57
  • It depends on which complexity bound you're looking at - for strlen, the lower bound worst-case is linear - but you cannot know the upper bound without knowing the implementation. However, given that the linear algorithm is kind-of obvious, common-sense dictates that it is implemented in that way. – ltjax Mar 11 '11 at 10:59
  • We rely a lot on the implementation to do the right thing. The case where it is important to specify the complexity in the standard is when there is a trade-off between complexity of different operations on the same data structure. See the effect of `list::splice` on `list<>::size()` for example. – AProgrammer Mar 11 '11 at 11:07
1

Yes, strlen is O(n), but in this particular example (with a string literal) a good optimizer can replace strlen(buf) with sizeof(buf). Some compilers do.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203