计算计算复杂度(Big-O)

时间:2013-05-06 13:49:45

标签: algorithm for-loop big-o computation-theory

Algorithm 1. QUEUESTUFF(n)
Input: Integer n
1) Let Q = an empty Queue
2) For i = 1 to n
3) Q.Enqueue(i)
4) End For
5) For i = 1 to n-1
6) Let X = Q.Dequeue()
7) End For
8) Let X = Q.Dequeue()
Output: The contents of X

What is the computational complexity O(n) for algorithm QUEUESTUFF?

第一个For循环只是n,第二个嵌套的是n-1。那么这会使O(n):

O(2n-1)只做(n + n) - 1

通过做(n * n) - 1

或者它是O(n ^ 2 - 1)

感谢您的帮助,我只想澄清一下。我的猜测是,因为我们有一个嵌套的For循环,我们必须n乘n-1,但我只是认为我可以通过得到别人的意见来更好地保证自己。

2 个答案:

答案 0 :(得分:0)

感谢Smoore得到了答案。由于循环不是嵌套的,因此Big-O将为O(2n-1)。

答案 1 :(得分:0)

有两个独立的(非嵌套的)for循环。 n项被排队,然后n个项目出列,给出了入队或出队的复杂性O(n)倍的复杂性。如果队列操作复杂度为O(1),则过程的复杂度为O(n),但如果队列操作复杂度为O(ln n),则过程的复杂度为O(n ln n)。