简体   繁体   English

算法能否在最佳和最差情况下具有相同的时间复杂度?

[英]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-else语句时不同。

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 最坏情况/最佳情况:3n + 5

Big – O : O(n) 大– 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). 大O描述一个渐近量的上限(小O描述一个渐近量的下限(例如算法的时间复杂度)。 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. 实际上,有一种特殊的表示法来给出渐近紧的边界(当大o与小o相同时,这是您得到的),这称为大theta表示法。

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. "number"固定的情况下,您的程序没有最坏的情况或最佳情况-它始终执行"number"迭代,因此它具有线性复杂度。
For formal mathematical definitions see these articles: 有关正式的数学定义,请参见以下文章:
http://en.wikipedia.org/wiki/Analysis_of_algorithms http://en.wikipedia.org/wiki/Analysis_of_algorithms
http://en.wikipedia.org/wiki/Big_O_notation 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). 在这种情况下,最坏情况的复杂度与最坏情况= 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). 无论输入是什么,该算法始终执行相同的操作(否/否则)。

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

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