For Java ArrayList, is it accurate to say add and remove by index run in amortized constant time, meaning on average it is constant time (in rare cases linear time by setting up the memory so future operations are faster)?
-
Did you see stackoverflow.com/questions/7910283/… ?user180100– user1801002016-10-02 17:56:06 +00:00Commented Oct 2, 2016 at 17:56
-
Yes but that didn't seem index based. I'm talking only indexes.Sean Hill– Sean Hill2016-10-02 17:58:26 +00:00Commented Oct 2, 2016 at 17:58
-
General performance of ArrayList and LinkedList methods are answered in this answer. It also contains adding an element at an index, or removing an element at an index.Tunaki– Tunaki2016-10-02 18:04:38 +00:00Commented Oct 2, 2016 at 18:04
2 Answers
No, this would not be accurate to say that insertion and removal of elements from ArrayList by index is amortized constant time, because there is no amortization going on for copying of data.
Only list expansions and their associated copying are amortized, because they happen infrequently*. However, this requires insertions at the end of the list.
When you insert at the beginning of the list, expansions are still amortized, but copies required to move elements by 1 position happen on every call, and are not amortized.
* In order to be able to amortize the cost of an operation you need a mix of "cheap" and "expensive" operations. In this situation you can split the total cost among all operations, getting you a lower result.
6 Comments
k elements in the middle of an n-element list is O(k*n/2).For add(Object) yes, but for remove(int index) it's constant time only if you're removing the last element, since otherwise the elements are shifted to remove any nulls from the middle of the array.
Index based add (and remove from not last position) aren't amortized constant time, they're linear time.
15 Comments
add() is append to end. It's constant unless the array needs to be resized.