I have a collection of paired numbers and need to efficiently find the set of pairs which encompass a given value.
Given the following representation of a number pair
public class Line
{
public double Start { get; set; } //is always < end
public double End { get; set; }
}
The collection of Lines
could be visually laid out like the below (black lines)
The perpendicular red line is the intersection criteria (just a simple number like 10.123)
I'm looking for an efficient algorithm that returns only the black lines that intersect with the red, based on the assumption that the frequency of search executions is greater than the frequency of Line
additions to the collection. (and obviously assume the collection is large)
My less than optimal solution so far is to
- Insert Lines as they are created into two sorted lists. One sorted on
Start
, the other Sorted onEnd
- Binary Search on the start ordered list to find the index of the first line where the start is greater than the intersection criteria. (in theory all lines including and after this index are non intersecting)
- Repeat similar logic in (2) for the end ordered list
- Compare indexes and pick the list with the lowest remaining iterations to resolve
- Iterate through the remainder of that chosen list manually looking for an intersection