Merging Ordered Intervals
An interval union routine sorts by start and keeps the furthest active end while consecutive ranges overlap.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a contained interval
For \([2,8),[3,4),[7,10)\), the short second interval leaves the active end at eight. The third merges to extend it to ten. The update should take the maximum end each time. Interval records give the endpoints their meaning.
Decide whether to combine neighbors
The half-open ranges \([1,3)\) and \([3,5)\) are disjoint but their union can be represented as \([1,5)\). Keep them separate if a visible reservation boundary matters. Postconditions should capture the chosen representation.[1]
Use a gap and a containment case in the trace
Start with ordered half-open intervals [1,5), [2,4), [5,7) and [9,10). If adjacent intervals should coalesce, the first three combine into [1,7). The contained interval ending at four must never shorten the accumulated endpoint. See interval representations.
Current [1,5), read [2,4) → end max(5,4)=5
Read [5,7) → adjacency allowed, end 7
Read [9,10) → gap, emit [1,7)
End → emit [9,10)
Read the desired result before picking the comparison
If intervals describe existing reservations and retaining their boundaries matters, touching intervals may stay separate. For a union of coverage, coalescing adjacent half-open intervals preserves the set. Test an actual overlap, a touch, and a gap.