[英]Asymptotic growth rate of a double while loop algorithm with an outer loop executed log(n) times
What is the asymptotic growth rate (depending on n
) of this algorithm ? 这个算法的渐近增长率(取决于
n
)是多少?
i = 1; // executed 1 time
while( i ≤ n) {
j = 1; // executed log(n) times
while( j ≤ i) {
j = j + 1; // ?
}
i = 2*i; // executed log(n) times
}
When n equals 10 : 当n等于10时:
| i iterations | j itérations
| i=1 | j=1
| i=2 | j=1 j=2
| i=4 | j=1 j=2 j=3 j=4
| i=8 | j=1 j=2 j=3 j=4 j=5 j=6 j=7 j=8
The outer loop(i) affectations are executed log(n)
times 外循环(i)影响执行
log(n)
次
How many times is the inner loop(j) affectation executed ? 内循环(j)执行多少次?
This should be O(n)
. 这应该是
O(n)
。
The last iteration of the outer loop has n
iterations of the inner loop. 外循环的最后一次迭代具有内循环的
n
次迭代。 The second-to-last iteration of the outer loop has n/2
iterations of the inner loop. 外循环的倒数第二次迭代具有内循环的
n/2
次迭代。 The third-to-last iteration has n/4
: 倒数第三次的迭代次数为
n/4
:
n + n/2 + n/4 + ... = 2*n
See geometric progressions for the formula that allows you to compute the sum. 请参阅允许您计算总和的公式的几何进度 。
When n is four, the last execution of the outer loop causes the inner loop to execute 4 times. 当n为4时,外循环的最后一次执行导致内循环执行4次。 When you double n from 4 to 8, the outer loop is executed one more time, and on that last execution of the outer loop the inner loop is executed 8 times.
当你将n从4加倍到8时,外循环再次执行,并且在最后一次执行外循环时,内循环执行8次。 Double it again to 16, and the outer loop will execute once more, with the inner loop going 16 times.
将它再次加倍到16,外部循环将再次执行,内部循环将执行16次。 So doubling the input causes a doubling in the execution time (plus the time for that one more outer loop, which become insignificant as n gets large).
因此,输入加倍会导致执行时间加倍(再加上一个外循环的时间,当n变大时变得无关紧要)。
So O(n). 所以O(n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.