What is the complexity of the time for the following code?


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; ++i)
        while(j < n && arr[i] < arr[j])

j is not reset to 0 with every iteration of the outer loop. As such, it runs to n-1 just once, same as i does. So you have two parallel/intermingled iterations from 0 to (at most) n-1.

In every step, the program increases i by one. The program terminates when i reaches n. The "outer loop" is run n times.

There is also an "inner loop" about j. But all it does is increase j until it reaches i (at most, sometimes it does less). j is never decreased. So that part is also run at most n times in total (not n times for each iteration of the "outer loop").