Say I have a large collection of elements.
Each element has a "position" field, which is a positive integer.
None of the two elements have the same value for the position field.
The only supported collection operation: addElement (newElement, positionAfterElement), where:
- newElement is the new item to be added (its position is still unknown)
- positionAfterElement is an existing collection item.
The function guarantees that:
- position (position AfterElement) <position (newElement)
- no other element in the collection has a position between position (positionAfterElement) and position (newElement)
I can change the value of all positions of elements as I wish, but I want to minimize the number of changes (on average).
How do I implement addElement function?
I could just click all elements with higher positions at 1, but I'm sure there should be a better way to do this.
Thank you all for your help.
source
share