简体   繁体   中英

Recursive algorithm complexity analysis

I am trying to analyze the complexity of this algorithm but I am not sure if its recurrence equation is T (n / 2) + 2n, could you help me? size of v > 100

bool pareado(int v[], int left, int right) {
    bool b;
    if (left >= right)
        b = true;
    else {
        int m = (left + right) / 2;
        bool baux = (abs(contarPares(v, left, m) - contarPares(v, m + 1, right)) <= 1);
        if (baux == false)
            b = false;
        else
            b = pareado(v, left, m) && pareado(v, m + 1, right);
    }
    return b;
}

The function "contarPares" is this:

int contarPares(int v[], int i, int j) {
    int count = 0;
    for (int k = i; k <= j; k++) {
        if ((v[k] % 2) == 0)
            count++;
    }
    return count;
}

Your pareado function has complexity O(n) [ for n = right-left ] before recursing. Given that on each recursion step you partition your input range, and handle them separately, you still have to iterate over the entire range once (for any iteration depth) in the worst case.

How many recursion depths are there? In the worst case you must wait until contarPares returns 0 because it has no input left, ie its range is empty. Given that you always half your input range, this will take log(n) recursions.

Since each depth costs O(n) and you have O(log(n)) depths, you come down to a total of O(n*log(n)) .

Of course depending on your input array, you may terminate much earlier, but you won't exceed the limit given above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM