Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is inserting at the end of a dynamic array O(1) while inserting in the middle is O(n)?

Accordingly to the Wikipedia article on dynamic arrays, inserting/deleting at the end of the array is O(1) while inserting/deleting from the middle is O(n). Why exactly is that?

Also - if I have a dynamic array with 5 elements and I insert a new element at position 6 the operation is O(n) whereas if I use the function to append to the end of the array it is O(1). Isn't this the same operation assuming the array doesn't need to resize in either case? Or does appending to the dynamic array really insert the new element somewhere besides position 6?

Thanks!

EDIT: I think my main confusion is the difference between inserting at the end of the array and inserting at a specific position that is equivalent to the end of the array.

I suppose a pointer to the memory address of the end of the array is kept handy and that is why the append operation is quick. Conversely, if I specify a precise position (even if it is the end of the array) it won't know that inserting at that position is tantamount to using the aforementioned memory address so it has to traverse the entire array, eh?

like image 937
Rob Sobers Avatar asked Dec 12 '25 20:12

Rob Sobers


2 Answers

To insert at the end of an array, you simply have to put the item there.

To insert into the middle of an array, you need to move the items after that point up by one.

To delete from the end of an array, you just drop its count by one.

To delete from the middle you have to do that and shift the other items down.

It's the shifting that turns it into O(n).

like image 58
paxdiablo Avatar answered Dec 15 '25 09:12

paxdiablo


The order of magnitude would depend entirely on what sort of data structure the "dynamic array" actually is ("dynamic array" isn't a strictly defined data structure, it's more of a desired result achieved by employing a particular data structure). The example that you give would be that reflect by a dynamic array achieved by employing a linked list. Adding to the end could be O(1) if the list structure kept a pointer to the final element. Inserting (regardless of the index) would require traversing the linked list, meaning one operation per node up until the desired index.

like image 33
Adam Robinson Avatar answered Dec 15 '25 10:12

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!