简体   繁体   中英

Finding Time Complexity Of This Algorithm

I'm trying to find the time complexity of this algorithm, I tried calculating it using T(n) , assumed that T(n) = 2T(n-1) + Const and got O(n) as a result.

bool sum(int arr[], int x, int n, int index){
    if(x == 0 && index == 3)
        return true;
    if(n == 0)
        return false;
    if (index == 3)
        return false;

    if(sum(arr+1, x-arr[0], n-1, index + 1))
        return true;
    return sum(arr+1, x, n-1, index);
}

The top call starts with index = 0. Basically I'm trying to see if there is a triple that sums to a given value x.

Am I missing something?

First of all, T(n) = 2T(n-1) + Const would make T(n) be in O(2^n), not O(n). This would be the runtime if you didn't have the index == 3 stopping condition. But this stopping condition decreases the runtime significantly.

One way to find the time complexity is to count the number of leaves in the recursion tree (ie number of times a stop condition was reached). Each leaf with index == 3 corresponds to a choice of 3 out of n elements, so there are C(n, 3) such nodes. Leaves with n == 0 and index < 3 corresponds to a choice of 0, 1, or 2 elements, ie C(n, 0) + C(n, 1) + C(n, 2). The total number of leaves is thus O(n^3).

Since the number of inner nodes (calls which do not reach a stop condition and thus make recursive calls) is about equal to the number of leaves, and each call does O(1) work not including the recursive calls, the total runtime is O(n^3).

Another way to get the same result is to consider T(n, index) :

T(n, 3) = C = O(1)
T(n, 2) = T(n-1, 3) + T(n-1, 2) + C = O(n)
T(n, 1) = T(n-1, 2) + T(n-1, 1) + C = O(n^2)
T(n, 0) = T(n-1, 1) + T(n-1, 0) + C = O(n^3)

Given that the top-level call is assumed to be made with index == 0 (from comments), the algorithm is O(n 3 ). Ignore the details of the implementation, and consider more abstractly what it is doing:

  • It performs a linear scan over array arr , where
    • for each element e , it performs a linear scan over the tail of arr starting after e , where
      • for each element f , it performs a linear scan over the tail of arr starting after f , where
        • for each element g , it checks whether e + f + g == x

The boundary case is the one in which no triplet of elements sums to x , and in that case the procedure does not end until all the scans are complete. As should be clear from that description, the recursion is equivalent to a triply-nested loop.

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