1

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?

3
  • That PDF seems to nicely explain how it's derived, can you tell us what you're not understanding so the answers can better address the question? Commented Oct 14, 2013 at 21:00
  • 1
    Also remember that for the purpose of asymptotic analysis, O(2N) = O(N) Commented Oct 14, 2013 at 21:02
  • I'm not confused about the amortized insertion time, which is 2 units, making the time of adding N elements 2N. I'm confused about adding just one element: Why is it 2N? Commented Oct 14, 2013 at 21:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.