开发者

Order of Complexity of standard lib functions

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 < len开发者_运维知识库gth; 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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜