We have a number of items which the end user will be able to organize into a desired order. The set of items is unordered, but each item contains a sort key which can be modified.
We're looking for an algorithm that would allow generating a new sort key for an item that is added or moved to be either the first item, last item, or between any two items. We're hoping to only have to modify the sort key of the item being moved.
An example algorithm would be to have each sort key be a floating point number, and when placing an item between two items, set the sort key to be their average. Placing an item first or last would take the outermost value +- 1.
The problem here is that floating point precision could cause the sorting to fail. Using two integers to represent a fractional number could similarly have the numbers become so large that they couldn't be accurately represented in regular numerical types (e.g. when transferring as JSON). We wouldn't want to use BigInts.
Is there a suitable algorithm for this that would work, for example, using strings, which wouldn't be affected by these shortcomings?
We're not looking to support huge numbers of moves, but the algorithm described above could fail on a double-precision floating points number after about 50 moves.
A, B, C
--A, AA, B, C
--A, AA, AB, B, C
--A, AA, AAA, AAB, AAC, AB, AC, B, C
. Of course, you would probably want to space your letters out more so that the strings don't grow so quickly, but it can be done.