Time complexity - recursive call

90 views Asked by At

I am trying to understand how to compute the time complexity of an algorithm .

I have this piece of code: This is the whole method:

public void solve(int i) {
    if(i < 2) {
        return;
    }
    solve(i-1); //recursive call
    int x = v[n-i];
    for(int j = n-i+1; j < n; j++) {
        if(x > v[j]) {
            count++;
        }
    }
    return;
}

I think the complexity is O(n). Am I right?

Thanks

2

There are 2 answers

1
Alexey A. On BEST ANSWER

The complexity should be O(N^2) as you will have N + (N-1) + (N-2) + 1 = N ( N + 1 ) / 2 iterations in worst case.

0
MeNa On

The complexity is O(i^2), n here no matter.

The function will run i times (until i<2). each iteration will run i times (n-(n-i+1)=i-1).

We can call it O(N^2) when N mention to i.

Note! N and n are not the same here!