简体   繁体   中英

Worst-case time for adding 1 element to expanding array

Suppose we have an expanding array that doubles in size when we try to add something to it but it is filled.

According to the bottom of the slide "Amortization: Expanding Vectors" the worst-case time for adding one element is 2N, not N? Why is this?

I thought it would be N because copying N elements to the new, double sized array, would take N time.

For example, say I'm adding just one element to a filled array of size 4. It would go like this:

  1. Make new array of size 8 (double of 4).
  2. Copy all of elements of original array to new array (copy 4 times).
  3. Set 5th element of the new array to the additional element (copy 1 time).

So that would copy elements 5 times, which is N + 1, not 2N?

The operations needed for adding an element to an exanding array is O(2N) because first you need to go through the whole array and check for empty space with O(N). Because this is the worst case there isn't any and you have to create a new array and copy the whole content from the first to the new array with O(N). Both operations combined result in O(2N).

When you think of array length the length is actually the size that is reserved for the array and not the number of elements inside. That is why you need to loop through the whole array for an empty space if you did not save the number of elements anywhere. I am speaking of 'empty space' because it is not stated that just elements were added and none were deleted inside the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM