为什么向量数组翻倍? [英] Why is vector array doubled?

查看:296
本文介绍了为什么向量数组翻倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么经典的实现载体(ArrayList中用于Java的人)的两倍或三倍四倍它的内部数组大小在每个扩展呢?

Why does the classic implementation of Vector (ArrayList for Java people) double its internal array size on each expansion instead of tripling or quadrupling it?

推荐答案

在计算的平均时间插入一个载体,你需要允许非生长刀片和不断增长的插件。

When calculating the average time to insert into a vector, you need to allow for the non-growing inserts and the growing inserts.

call操作的总数插入 N 的项目 0 <子>总 ,平均 0 <子>平均值

Call the total number of operations to insert n items ototal, and the average oaverage.

如果您插入 N 的项目,您可以通过一个因素增加 A 的要求,则有 0 <子>总 = N +&Sigma公司; A [0℃ I&LT; 1 + LN <子> A N] 的操作。在最坏的情况下,你使用的 1 / A的分配存储的

If you insert n items, and you grow by a factor of A as required, then there are ototal = n + ΣAi [ 0 < i < 1 + lnAn ] operations. In the worst case you use 1/A of the allocated storage.

直观地看, A = 2 意味着在最坏的情况你有 0 <子>总 = 2 ,所以 0 <子>平均值 的是O(1),以及最坏的情况下使用该分配的存储的50%。

Intuitively, A = 2 means at worst you have ototal = 2n, so oaverage is O(1), and the worst case you use 50% of the allocated storage.

对于一个较大的 A ,你有一个较低的 0 <子>总 的,但更浪费的存储。

For a larger A, you have a lower ototal, but more wasted storage.

对于较小的 A 0 <子>总 的较大,但你就不会浪费那么多的存储。只要它的增长几何,它仍然是O(1)摊销插入时间,但常会获得更高的。

For a smaller A, ototal is larger, but you don't waste so much storage. As long as it grows geometrically, it's still O(1) amortised insertion time, but the constant will get higher.

有关的生长因子1.25(红色),1.5(青色),2(黑),3(蓝色)和4(绿色),这些图显示点和平均大小效率(尺寸/分配空间的比率;更多的是更好)上插入/操作的左侧和时间效率(比率;右侧插入400000项越多越好)。达到对所有生长因子之前,为了调整100%空间利用效率;对于这样的 A = 2 显示25%至50%,和空间效率约50%,这有利于大多数情况下,时间效率:

For growth factors 1.25 ( red ), 1.5 ( cyan ), 2 ( black ), 3 ( blue ) and 4 ( green ), these graphs show point and average size efficiency ( ratio of size/allocated space; more is better ) on the left and time efficiency ( ratio of insertions / operations; more is better ) on the right for inserting 400,000 items. 100% space efficiency is reached for all growth factors just prior to resizing; the case for A = 2 shows time efficiency between 25% and 50%, and space efficiency about 50%, which is good for most cases:

有关的运行时间,例如Java,阵列零填充,所以操作分配的数量是正比于数组的大小。考虑到这给降低了时间效率估计数之间的差异:

For runtimes such as Java, arrays are zero filled, so the number of operations to allocate is proportional to the size of the array. Taking account of this gives reduces the difference between the time efficiency estimates:

这篇关于为什么向量数组翻倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆