I have a ray, I need to find the closest line segment that it hits. I think it's possible to do this in O(log n) time if I sort the line segments first, but I can't remember how to sort them... I think some sort of tree would work best, but how do I sort them by both start and end point? I would also like fast insertions into this data structure if possible. 

There's lots of code for one ray vs one line segment, but I need something for one ray vs many line segments... I don't know what terms to google for.

A link to an appropriate article is good, C++ code is even better. Thanks! :)

PS: The line segments are actually the edges of a non-self-intersecting polygon, sorted in CCW order... but I think there may be some advantage to sorting them in a different fashion?

This is all 2D.

---

On second thought, I'm not entirely sure this *is* possible. Some sort of spatial partitioning might help, but otherwise, I can't think of any way to sort the lines so that they could be compared with an arbitrary ray.