Search code examples
c#listbinary-search

Can I use BinarySearch over a List of (start, end) Ranges to find a number covered by one Range


I have a list of ranges, for example: (0, 1), (1, 4), (4, 8), (8, 14), (14, 20),
where Range is class with Start & End.

Can I apply a BinarySearch for searching a segment which contains value 10?
Any other way to implement this?


Solution

  • I've wrote my own function:

    public Range BinarySearch(double position)
    {
        Range part = null;
    
        int from = 0;
        int to = Count - 1;
        while (from < to)
        {
            int middle = (from + to) / 2;
            part = this[middle];
    
            switch (part.CompareTo(position))
            {
                case 1:
                    from = Math.Min(middle + 1, to);
                    break;
                case -1:
                    to = Math.Max(middle - 1, from);
                    break;
                case 0:
                    from = to = middle;
                    break;
            }
        }
    
        return this[to];
    }