简体   繁体   English

递归算法复杂度分析

[英]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?我正在尝试分析该算法的复杂性,但我不确定它的递推方程是否为 T (n / 2) + 2n,您能帮帮我吗? size of v > 100 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: function“contarPares”是这样的:

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.您的pareado function 在递归之前具有复杂性 O(n) [ for n = right-left ]。 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.在最坏的情况下,您必须等到contarPares返回0 ,因为它没有输入,即它的范围是空的。 Given that you always half your input range, this will take log(n) recursions.鉴于您总是输入范围的一半,这将需要 log(n) 递归。

Since each depth costs O(n) and you have O(log(n)) depths, you come down to a total of O(n*log(n)) .由于每个深度都花费 O(n) 并且您有 O(log(n)) 深度,因此您总共需要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.当然,根据您的输入数组,您可能会更早终止,但不会超过上面给出的限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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