Fastest way to search a number in a list of ranges

前端 未结 5 848
终归单人心
终归单人心 2020-12-19 04:12

I have the following code to find a match for a number in a list of ranges.

public class RangeGroup
{
    public uint RangeGroupId { get; set; }
    public u         


        
5条回答
  •  被撕碎了的回忆
    2020-12-19 04:41

    Since you indicated that RangeGroups are added in order of RangeGroup.Low and that they do not overlap, you don't need to do any further pre-processing. You can do binary search on the RangeGroups list to find the range (warning: not fully tested, you'd need to check some edge conditions):

    public static RangeGroup Find(uint number) {
        int position = RangeGroups.Count / 2;
        int stepSize = position / 2;
    
        while (true) {
            if (stepSize == 0) {
                // Couldn't find it.
                return null;
            }
    
            if (RangeGroups[position].High < number) {
                // Search down.
                position -= stepSize;
    
            } else if (RangeGroups[position].Low > number) {
                // Search up.
                position += stepSize;
    
            } else {
                // Found it!
                return RangeGroups[position];
            }
    
            stepSize /= 2;
        }
    }
    

    The worst-case run time should be around O(log(N)), where N is the number of RangeGroups.

提交回复
热议问题