确定算法的最坏情况复杂度
有人可以向我解释一下如何确定算法的最坏情况复杂性吗? 我知道我们需要使用方程 W(n) = max{t(I)|I D 的元素),其中 D 是大小为 n 的输入集。 我是否计算每个元素 I 执行的操作数,然后取其最大值? 有什么更简单的方法可以实现这一点?
Can someone please explain to me how one can determine the worst-case complexity of an algorithm. I know that the we need to use the equation W(n) = max{t(I)|I element of D), where D is the set of inputs of size n. Do I calculate the number of operations performed for each element I and then take its max? What easier way is there to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从等式开始思考有点倒退。 您真正关心的是可扩展性,或者,当您增加输入大小时它将做什么。
例如,如果您只有一个循环,那么您就有一个时间复杂度为 O(n) 的算法。 如果你在另一个循环中有一个循环,那么它就会变成 O(n^2),因为它现在必须对任何大小 n 个输入执行 n^2 件事情。
当您谈论最坏的情况时,您通常谈论的是非确定性算法,其中可能有一个可能提前停止的循环。 为此,您要做的是假设最坏的情况并假装循环将尽可能晚地停止。 所以如果我们有:
会说最坏的情况是 O(n^2)。 尽管我们知道中间循环很可能会提前退出,但我们仍在寻找可能的最差性能。
Starting from the equation is thinking of it a bit backwards. What you really care about is scalability, or, what is it going to do as you increase the size of the input.
If you just have a loop, for instance, you have a O(n) time complexity algorithm. If you have a loop within another loop though, it becomes O(n^2), because it must now do n^2 many things for any size n input.
When you are talking about worst case, you are usually talking about non deterministic algorithms, where you might have a loop that can stop prematurely. What you want to do for this is assume the worst and pretend the loop will stop as late as possible. So if we have:
We would say that the worst-case is O(n^2). Even though we know that it is very likely that the middle loop will bust out early, we are looking for the worst possible performance.
该方程更多的是一个定义,而不是一个算法。
所讨论的算法除了输入的大小之外还关心其他什么吗? 如果不是,那么计算 W(n) 就“容易”。
如果确实如此,请尝试提出病态的输入。 例如,使用快速排序,排序输入是病态的可能是相当明显的,您可以进行一些计数以查看它需要 O(n^2) 步骤。 此时,您可以
#1 的示例:
#2 的示例:
在这种情况下#2 就容易多了。
That equation is more of a definition than an algorithm.
Does the algorithm in question care about anything other than the size of its input? If not then calculating W(n) is "easy".
If it does, try to come up with a pathological input. For example, with quicksort it might be fairly obvious that a sorted input is pathological, and you can do some counting to see that it takes O(n^2) steps. At that point you can either
Example of #1:
Example of #2:
In this case #2 is a lot easier.