Efficiency of growing a dynamic array by a fixed constant each time?

送分小仙女□ 提交于 2019-12-04 07:56:48
templatetypedef

If you grow by some fixed constant C, then no, the runtime will not be O(n). Instead, it will be Θ(n2).

To see this, think about what happens if you do a sequence of C consecutive operations. Of those operations, C - 1 of them will take time O(1) because space already exists. The last operation will take time O(n) because it needs to reallocate the array, add space, and copy everything over. Therefore, any sequence of C operations will take time O(n + c).

So now consider what happens if you perform a sequence of n operations. Break those operations up into blocks of size C; there will be n / C of them. The total work required to perform those operations will be

(c + c) + (2c + c) + (3c + c) + ... + (n + c)

= cn / c + (c + 2c + 3c + ... + nc / c)

= n + c(1 + 2 + 3 + ... + n / c)

= n + c(n/c)(n/c + 1)/2

= n + n(n/c + 1)/2

= n + n2 / c + n / 2

= Θ(n2)

Contrast this with the math for when you double the array size whenever you need more space: the total work done is

1 + 2 + 4 + 8 + 16 + 32 + ... + n

= 1 + 2 + 4 + 8 + ... + 2log n

= 2log n + 1 - 1

= 2n - 1

= Θ(n)


Transplanted from SO Documentation.

Sums of powers of 2 — 1 + 2 + 4 + 8 + 16 + …

The sum

20 + 21 + 22 + ... + 2n-1

simplifies to 2n - 1. This explains why the maximum value that can be stored in an unsigned 32-bit integer is 232 - 1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!