简体   繁体   中英

How to calculate order-complexity of the following algorithm

I'm trying to calculate the time complexity of this code that sums the odd numbers of an array. I have done two methods and now I need to calculate the order complexity O(n)

This one is done by weak post-condition.

private static int sumaImparDebilit(int t[], int desde, int hasta) {
    if (desde==hasta) {
        if ((t[desde] % 2) == 1) {
            return t[desde];
        }
        return 0;
    } 
    if (t[desde]%2 == 1) {
        return (t[desde] + sumaImparDebilit(t,(desde+1),hasta));
    }
    return (sumaImparDebilit(t,(desde+1),hasta));

}

This one is done by strong pre-condition.

private static int sumaImparFortalec(int t[], int hasta, int limite, int parcial) {
    if (hasta <= limite) {
        if ((t[hasta] % 2) == 1) {
            return sumaImparFortalec(t,(hasta + 1),limite,(parcial + t[hasta]));
        } else {
            return sumaImparFortalec(t,(hasta + 1),limite,(parcial));
        }
    }
    else {
        return parcial;
    }
}

I don't know what you mean by “weak” and “strong” conditions, but both have time complexity O(n) and employ (for no good reason) recursion.

Surely this is simplest, and fastest:

int sum = 0;
for (int i = 0; i < t.length; i++)
    if (t[i] % 2 == 1)
        sum += t[i];

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