Let's say I have a large collection of elements.
Each element has a "position" field, which is a positive integer.
No two elements have the same value for the field "position".
The only supported operation of the collection is: addElement(newElement, positionAfterElement), where:
- newElement is the new element to be added (its position is unknown for now)
- positionAfterElement is an existing element of the collection.
The function will guarantee that:
- position(positionAfterElement) < position(newElement)
- no other element in the collection has a position between position(positionAfterElement) and position(newElement)
I can change the value of all the element positions as I wish but I want to minimize the number of changes (on average).
How should I implement the addElement function?
I could just push all the elements with higher positions by 1 but I am pretty sure there must be a better way to do this.
Thanks all for your help.