r/algorithms • u/ClickOk5811 • 20h ago
Discussion Sweep-line segment intersection: a tie-break bug that changes the answer
Given a set of line segments, report all intersection points. Standard sweep-line: sort events by x, then y; maintain an active set ordered by y at the sweep line; check neighbors when segments enter or leave.
The part that rarely gets emphasized is the event tie-break. When two segments share the same left endpoint x, you order them by y. But when the sweep line reaches an endpoint shared by multiple segments, the order you process endpoints at that exact x determines which pairs are “adjacent” in the active set at that moment, and a wrong tie-break can make you miss an intersection entirely.
I put together a minimal reproducible example in Python (shapely only for ground truth, the sweep is pure Python). I have not run the numbers myself, so treat the expected output as a hypothesis, not a measurement:
from shapely.geometry import LineString, MultiPoint
from sortedcontainers import SortedList
def sweep_intersections(segments):
"""
segments: list of ((x1,y1),(x2,y2)) with x1 <= x2.
Returns list of intersection points.
"""
events = []
for i, ((x1, y1), (x2, y2)) in enumerate(segments):
events.append((x1, y1, 'L', i))
events.append((x2, y2, 'R', i))
# Sort by x, then y, then type (L before R at same point)
events.sort(key=lambda e: (e[0], e[1], 0 if e[2] == 'L' else 1))
active = SortedList(key=lambda i: y_at(segments[i], current_x))
intersections = set()
def y_at(seg, x):
(x1, y1), (x2, y2) = seg
if x1 == x2:
return y1
return y1 + (y2 - y1) * (x - x1) / (x2 - x1)
def check_pair(i, j, x):
if i is None or j is None:
return
# compute intersection of segments i and j near sweep line x
...
for x, y, typ, i in events:
if typ == 'L':
pos = active.add(i) # conceptual
neighbors = active.neighbors(i)
check_pair(i, neighbors.left, x)
check_pair(i, neighbors.right, x)
else:
neighbors = active.neighbors(i)
check_pair(neighbors.left, neighbors.right, x)
active.remove(i)
return intersectionsThe subtle point: at a shared left endpoint, should you insert segments in order of slope (steepest first), or by y at x+ε? If you insert by y at the endpoint itself, two segments starting at the same point compare equal, and the tie-break in your sorted container becomes arbitrary — which changes which pairs you test for intersection.
Questions:
- Is the slope-at-endpoint tie-break the standard way to handle this, or is there a cleaner formulation?
- Has anyone hit a case where this specific ordering produced a missed intersection in practice?
- Any recommendations for a Python ordered-set that lets you inject a custom x-dependent comparator without rebuilding on every event?
I haven’t tested this with real coordinates yet, if someone wants to run it, I’d love to see whether the naive tie-break actually drops an intersection on a concrete case.