简体   繁体   中英

Can algorithms have the same best- and worst-case time complexity?

Is it possible for an algorithm/program to have the same worst-case and best-case time?

For example:

public static int factorial(int number)
{
    factorial = 1; 
    for (i = 1; i <= number; i++) 
        factorial = factorial * i;
}

It's a program segment for the factorial problem, and I was trying to solve for the time complexity. It seems to have no worst and best case time, since whatever input you may have it will still go through the rest of the code, unlike when you have if-else statements.

If that's the case should I assume that what ever I get from this code it would be the best, worst and average case time?

Did I get this right?

public static int factorial(int number)
    {
        factorial = 1;                   // 1
        for (i = 1; i <= number; i++)    // 1+3n
            factorial = factorial * i;   // 2
        return factorial;                // 1
    }

Worst Case/Best Case: 3n+5

Big – O : O(n)

Of course. Big O describes an upper bound, while little o describes a lower bound on some asymptotic quantity (such as the time complexity of an algorithm). There is actually a special notation for giving bounds which are asymptotically tight (which is what you get when the Big o is the same as the little o), which is called big theta notation.

In your case when "number" is fixed, your program has no worst or best case - it always does "number" iterations, so it has a linear complexity.
For formal mathematical definitions see these articles:
http://en.wikipedia.org/wiki/Analysis_of_algorithms
http://en.wikipedia.org/wiki/Big_O_notation

In this case the complexity for the bast case is the same as the worst case = O(n). Exactly for the reason you pointed out. No matter what the input is, the algorithm always performs the same actions (no if/else).

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