Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big o notation and recursive functions

I am trying to learn Big-O notation but i have difficulties in calculating time complexity of recursive functions.

Can you help me to understand the time complexity of following example?

public int recursiveFunction(int n) {
    if (n == 0) {
        return 0;
    }

    return Math.max(recursiveFunction(rand(n)) + 2,recursiveFunction(n - 1));
}

public int rand(int n) {
    return new Random().nextInt(n - 1);
}

Thanks.

like image 799
user987654 Avatar asked Sep 23 '26 15:09

user987654


1 Answers

The time will depend on what rand(n) returns, but if you take the worst-case, this will be n-2. So the code simplifies to:

public int recursiveFunction(int n) {
    if (n == 0) {
        return 0;
    }

    return Math.max(recursiveFunction(n - 2) + 2,recursiveFunction(n - 1));
}

which has an asymptotic upper bound equal to that of:

public int recursiveFunction(int n) {
    if (n == 0) {
        return 0;
    }

    recursiveFunction(n-1);
    recursiveFunction(n-1);

    return 0;
}

which is a recursion with a depth of n and a branch factor of 2, so O(2^n) time-complexity.

like image 199
fgb Avatar answered Sep 25 '26 04:09

fgb