Dynamic array add at the end?

浪尽此生 提交于 2020-01-16 08:44:07

问题


Starting with a dynamic array of initially length = 4 and numElements = 0, show the array when we add the followings numbers at the end: 5, 19, 4, 6, -1.

The checkpoint (answer) I receive is [5, 19, 4, 6, -1, X, X, X], where X denotes the entries which can be ignored.

I have 2 silly questions:

  1. I thought insert at the end would make it [X, X, X, 5, 19, 4, 6, -1] instead of what it looks like right now in the answer?

  2. I initially though every time we add something in the array, the array would automatically double the its length, that is why we have the 3 X's at the end, making the total ending length is 8 instead of the initial size of 4. Is this correct?


回答1:


It works like this.

"Adding at the end" means appending to the end of the array. Let's do it first without worrying about the internals.

First the list is empty

[]

Then you insert 5

[5]

Then 19

[5, 19]

Then 4 then 6 then -1

[5, 19, 4]
[5, 19, 4, 6]
[5, 19, 4, 6, -1]

Now how does this look when we have arrays whose capacities are in multiples of 4. As you say, they do double in size when they fill up. So this is the progression:

X  X  X  X

5  X  X  X

5 19  X  X

5 19  4  X

5 19  4  6

5 19  4  6 -1  X  X  X

When inserting the first 4 elements, the block of 4 fills up. When inserting the 5th, we don't have room, so we have to double the capacity to 8, then put the 5th element in the first available slot.

So yes you are correct about doubling the capacity. But the array elements are always filled from the beginning with the unused slots at the end. If you put values at the end, you would have to shift them over to the left on every insertion, which would be very inefficient.



来源:https://stackoverflow.com/questions/58705931/dynamic-array-add-at-the-end

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