I am designing an algorithm that works as follows:
Suppose that there are N slots which are initially empty and each
slot is numbered uniquely.
As time goes by, items will arrive and get deposited into slots whose numbers match
the items’ numbers. However, the order in which items arrive are assumed to
be at random.
In the meanwhile, a merging algorithm will be regularly executed to merge adjacent occupied slots in such a way that the slots will grow more and more “connected” as time goes by and eventually become one large occupied slot, at which point the algorithm terminates.
P.S. my algorithm is serial. The merging part is activated regularly after a certain number
of new slots are occupied.
You are probably looking for something based on disjoint-set.
Start with
nsets, each for an empty slot, and “merge” [union] them once you fill two adjacent slots. This can be done by maintaining “highest” and “lowest” field in each root of each set.Once you enter an element, you need to find its root [easy to do with this data structure], and merge it with
set[root.highest+1]and withset[root.lowest-1]– if they are both already “filled”.Each merge will also have to modify the root.highest and root.lowest fields, but that can be easily done in
O(1), once you have found the new root.If you implement the disjoint set as forests, initialization time of the algorithm is
O(n)[wherenis the number of slots], and each insertion op isO(alpha(n))wherealpha(n)is the inverse ackerman function, which is sub-logarithmic.