我有一个类似下图所示的循环。我有兴趣为这个循环结构找到Big O.
for i = 1 to n { // assume that n is input size
...
for j = 1 to 2 * i {
...
k = j;
while (k >= 0) {
...
k = k - 1;
}
}
}
我可以收集的是:
那么n的大O应该是O(n ^ 3)还是会有不同的东西呢?
将会对这些问题及其解决方案的具体链接表示赞赏。
答案 0 :(得分:0)
让I(),M(),T()成为内循环,中循环和整个程序(最外循环)的运行时间。如果我们从内到外工作,我们得到:
Inner-most loop;
I(j) = Summation (1) //from k=0 to j
I(j) = j+1 //Using basic Summation expansion formula.
Middle loop
M(i) = Summation (I(j)) //from j=1 to 2i
M(i) = Summation (j+1) //from j=1 to j=2i with I(j)'s values
M(i) = Summation (j) + Summation (1) //both from j=1 to j=2i
Using the expansion formula for Summation (j) from j=1 to n is '(n(n+1)/2)' and the fact that Summation (1) from j=1 to n is 'n', we get:
M(i) = 2i^2 + 3i
Outer-most loop:
T(n) = Summation (2i^2 + 3i) //Summation from i=1 to n
T(n) = Summation (2i^2) + Summation (3i) //both summations from i=1 to n
T(n) = 2*Summation (2i^2) + 3*Summation (i) //both summations from i=1 to n
T(n) = (2(2n^3 + 3n^2 + n))/6) + (3(n(n+1))/2) //using summation expansion formulas
T(n) = (4n^3 + 15n^2 + 11n)/2
Which means Big O of n be T(n^3).
注意:汇总扩展的基本求和扩展公式可以在this链接的第一页找到
感谢提示@Paul Hankin