在范围列表中搜索数字的最快方法
问题内容:
我有以下代码来查找范围列表中数字的匹配项。
public class RangeGroup
{
public uint RangeGroupId { get; set; }
public uint Low { get; set; }
public uint High { get; set; }
// More properties related with the range here
}
public class RangeGroupFinder
{
private static readonly List<RangeGroup> RangeGroups=new List<RangeGroup>();
static RangeGroupFinder()
{
// Populating the list items here
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023238144, High = 1023246335 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023246336, High = 1023279103 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023279104, High = 1023311871 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023311872, High = 1023328255 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023328256, High = 1023344639 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023344640, High = 1023410175 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023410176, High = 1023672319 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023672320, High = 1023688703 });
RangeGroups.Add(new RangeGroup { RangeGroupId = 0, Low = 1023692800, High = 1023696895 });
// There are many more and the groups are not sequential as it can seen on last 2 groups
}
public static RangeGroup Find(uint number)
{
return RangeGroups.FirstOrDefault(rg => number >= rg.Low && number <= rg.High);
}
}
RangeGroup的列表包含大约5000000个项目,并且将大量使用Find()方法,因此我正在寻找一种进行搜索的更快方法。更改数据结构或以任何方式拆分数据都没有问题。
编辑:
所有范围都是唯一的,并且按“低”的顺序添加,并且它们不重叠。
结果:
使用ikh的代码进行了测试,结果比我的代码快大约7000倍。测试代码和结果可以在这里看到。
问题答案:
由于您指出RangeGroup
s是按的顺序添加的,RangeGroup.Low
并且它们不重叠,因此您无需进行任何进一步的预处理。您可以在RangeGroups
列表上进行二进制搜索以找到范围(警告:未经充分测试,您需要检查一些边缘条件):
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;
}
}
最坏情况下的运行时间应该在O(log(N))左右,其中N是RangeGroups的数量。