Put all the endpoints in one array and assign them polarity ( + then - ). Then sort the list.
When you go through the list, increasing the value, it is enough to update the counter of overlapping segments.
0+ 0.75- 0.5+ 1- 1.25+ 2-
then sorted,
0+ 0.5+ 0.75- 1- 1.25+ 2-
gives counts (initialized to 0 )
1 2 1 0 1 0
therefore, the interval boundaries (at transitions 0 to >0 or >0 to 0 )
0 1 1.25 2
This can also be done cleanly in place , without additional flags .
You sort the start and end values โโseparately, in place (do not move the Segments as a whole); thus, the polarities remain implicit.
Then cross the list as a merge of two sorted lists (using two independent indexes) and save the overlap counter. You can rewrite borders in place, since the result of the merge has no more intervals.
Beginning with
[0 0.75][0.5 1][1.25 2]
both lists are randomly sorted.
0 0.5 1.25 (+) 0.75 1 2 (-)
Go to the merge, which will select the items in order
+ + - - + -
and the end result is obtained by shifting the values
[0 1][1.25 2][xx]
In the case of ties at the borders, it is better to handle + and - in this order so that you do not select two equal borders.
Yves daoust
source share