嵌套循环的运行时间

时间:2015-10-11 17:35:32

标签: algorithm big-o asymptotic-complexity

我确信这个嵌套循环的运行时间是O(N * log(N))。内循环的运行时间是log(N),而外循环是N.

for (int i = 0; i < N; ++i) {
  for (int j = 1; j <= i; j *= 2) { 
  }
}

在内循环中,如果我将j *= 2更改为j *= 3,该怎么办?在这种情况下,结果会如何变化?

4 个答案:

答案 0 :(得分:3)

@Kevin是完全正确的,但我想我会展示一些实验结果。您可以通过创建一个计数器来轻松测试这一点,该计数器在每个内循环迭代中递增并运行不同的N值。然后可以使用time = a * N * log(N)形式进行拟合。对于案例j *= 2,我们得到系数a = 1.28。对于j *= 3,我们得到a = 0.839

enter image description here

我使用下面的MATLAB脚本生成了这个数字:

clear
clc
close all

nmin = 10;
nmax = 1000;

count1 = zeros(nmax - nmin + 1, 1);

for n = nmin: nmax

    k = 0;
    for i = 0: n - 1
        j = 1;
        while (j <= i)
            j = j * 2;
            k = k + 1;
        end
    end

    count1(n - nmin + 1) = k;

end

ns = (nmin: nmax)';

figure
hold on
plot(ns, count1, '--')

a1 = mean(count1 ./ (ns .* log(ns)))

fit1 = a1 * ns .* log(ns);
plot(ns, fit1)

%%

count2 = zeros(nmax - nmin + 1, 1);

for n = nmin: nmax

    k = 0;
    for i = 0: n - 1
        j = 1;
        while (j <= i)
            j = j * 3;
            k = k + 1;
        end
    end

    count2(n - nmin + 1) = k;

end

ns = (nmin: nmax)';

plot(ns, count2, '-.')

a2 = mean(count2 ./ (ns .* log(ns)))

fit2 = a2 * ns .* log(ns);
plot(ns, fit2)

xlabel('N')
ylabel('Time complexity')
legend('j *= 2', 'j *= 2 fit', 'j *= 3', 'j *= 3 fit', 'Location', 'NorthWest')

答案 1 :(得分:2)

它仍然是对数的。但是,它将按常数因子进行缩放(这与Big O分析无关)。

效果是对数的基数发生变化(见https://en.wikipedia.org/wiki/Logarithm#Change_of_base)。

答案 2 :(得分:0)

---------- [j = 2 * j]对于j&lt; I:-------------

j = 2*1 = 2 =>2^1
    2*2 = 4 =>2^2
    2*4 = 8 =>2^3
............. 2^k = n say n==i
if log applied on both side 2^k = n 
log(2^k) = logn
k = log_2(N) where 2 is the base

---------- [j = 3 * j]对于j&lt; I:-------------

j = 3*1 = 3  =>3^1
    3*3 = 9  =>3^2
    3*9 = 27 =>2^3
.............loop stop when 3^k = n say n==i
if log applied on both side 3^k = n 
log(3^k) = logn
k = log_3(N) where 3 is the base

答案 3 :(得分:0)

如果您熟悉数学公式并且对精确度更高,您可以有条不紊地使用Sigma表示法,如下所示:

enter image description here

blog开始: enter image description here