What is time complexity for the following code?

后端 未结 5 1110
刺人心
刺人心 2021-01-17 06:33

It seems the complexity of the following code should be O(n^2) but it\'s O(n), how?

void fun(int n, int arr[])
{
    int i = 0, j = 0;
    for(; i < n; ++         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 07:18

    Lets consider the worst case when the while loop is executed maximum no. of times. Initially: i=0 , j=0 => while loop does not gets executed since arr[0] = arr[0] i.e. j=0. Second iteration : i=1 , j=0 => while loop gets executed for the worst case i.e. j=1. Third iteration : i=2 , j=1 => while loop again gets executed for the worst case i.e. j=2. ... nth iteration : i=n-1 , j=n-2 => while loop again gets executed for the worst case i.e. j=n-1.

    So, by doing this exercise we can observe that every time j = i-1 except i=0 and j=0 OR we can say that the while loop is just running in parallel to the for loop and thus the no. of executions of the while loop is equal to the no. of executions of the for loop. Hence Order = O(n);

提交回复
热议问题