Is the time complexity of the empty algorithm O(0)?

后端 未结 14 2270
暗喜
暗喜 2020-12-12 21:29

So given the following program:


Is the time complexity of this program O(0)? In other words, is 0 O(0)?

I thought answering this in a separate question

14条回答
  •  再見小時候
    2020-12-12 22:13

    O(1) means the algorithm's time complexity is always constant.

    Let's say we have this algorithm (in C):

    void doSomething(int[] n)
    {
      int x = n[0]; // This line is accessing an array position, so it is time consuming.
      int y = n[1]; // Same here.
      return x + y;
    }
    

    I am ignoring the fact that the array could have less than 2 positions, just to keep it simple.

    If we count the 2 most expensive lines, we have a total time of 2.

    2 = O(1), because:

    2 <= c * 1, if c = 2, for every n > 1

    If we have this code:

    public void doNothing(){}
    

    And we count it as having 0 expansive lines, there is no difference in saying it has O(0) O(1), or O(1000), because for every one of these functions, we can prove the same theorem.

    Normally, if the algorithm takes a constant number of steps to complete, we say it has O(1) time complexity.

    I guess this is just a convention, because you could use any constant number to represent the function inside the O().

提交回复
热议问题