What is time complexity for the following code?

后端 未结 5 1082
刺人心
刺人心 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:03

    In the first look, the time complexity seems to be O(n^2) due to two loops. But, please note that the variable j is not initialized for each value of variable i.

    Hence, the inner j++ will be executed at most n times.

    The i loop also runs n times.

    So, the whole thing runs for O(n) times.

    Please observe the difference between the function given in question and the below function:

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

    }`

    Still not convinced ?

    Let's assume the array passed has its element in decreasing order. We will just dry run through the code :

                   Iteration 1 : i = 0, j = 0. arr[0] < arr[0] is false. So, the 
                                 inner while loop breaks.
                   Iteration 2: i =1, j = 0. arr[1] < arr[0] is true. j becomes 
                   Iteration 3 : i = 1, j = 1. Condition false. We break. Note 
                                that j will remain 1 and is not reset back to 0.
                   Iteration 4 : i = 2, j = 1. arr[2] < arr[1]. True. j = 2.
                   Iteration 5 : i = 2, j = 2. Condition false. Break.
                   Iteration 6 : i = 3, j = 2. arr[3] < arr[2]. True. j = 3.
                   Iteration 7 : i = 3, j = 3. Condition false. Break.
    

    As you can see, the inner while loop only runs once in this case. So, total iterations is 2 * N.

提交回复
热议问题