C#二进制搜索变量
列表已排序 我有一个列表,我想对它进行二进制搜索。T有StartIndex、EndIndex等成员 我可以用StartIndex对列表进行二进制搜索,即:我已经为此实现了IComparable 我需要将其稍微扭曲如下:我想找到一个StartIndex,它可能会偏离一个小值 例如:T.StartIndex=100 如果输入值为101且OffBy 1,则BinarySearch应返回此对象 我该怎么做 顺便说一句,我想知道如何使用列表中的默认binarysearch方法来实现这一点。这正是我感兴趣的,对自定义二进制搜索实现不感兴趣。如果使用C#二进制搜索变量,c#,.net,algorithm,search,binary-search,C#,.net,Algorithm,Search,Binary Search,列表已排序 我有一个列表,我想对它进行二进制搜索。T有StartIndex、EndIndex等成员 我可以用StartIndex对列表进行二进制搜索,即:我已经为此实现了IComparable 我需要将其稍微扭曲如下:我想找到一个StartIndex,它可能会偏离一个小值 例如:T.StartIndex=100 如果输入值为101且OffBy 1,则BinarySearch应返回此对象 我该怎么做 顺便说一句,我想知道如何使用列表中的默认binarysearch方法来实现这一点。这正是我感兴趣的
List.BinarySearch
,它将找到一个存在的确切位置,或者返回需要插入项的索引的位补码
因此,如果它返回一个负数,只需检查下一个和上一个项目(当然要注意端点),看看这两个项目是否在您想要的公差范围内
例如:
int index = list.BinarySearch(item);
if (index < 0)
{
int candidate = ~index;
if (candidate > 0 &&
Math.Abs(list[candidate - 1].StartIndex - item.StartIndex) <= tolerance)
{
index = candidate - 1;
}
else if (candidate < list.Count - 1 &&
Math.Abs(list[candidate + 1].StartIndex - item.StartIndex) <= tolerance)
{
index = candidate + 1;
}
else
{
// Do whatever you need to in the failure case
}
}
// By now, index is correct
int index=list.BinarySearch(项);
如果(指数<0)
{
int-candidate=~索引;
如果(候选项>0&&
Math.Abs(list[candidate-1].StartIndex-item.StartIndex)如果使用list.BinarySearch
,它将找到一个存在的确切位置,或者返回需要插入项的索引的位补码
因此,如果它返回一个负数,只需检查下一个和上一个项目(当然要注意端点),看看这两个项目是否在您想要的公差范围内
例如:
int index = list.BinarySearch(item);
if (index < 0)
{
int candidate = ~index;
if (candidate > 0 &&
Math.Abs(list[candidate - 1].StartIndex - item.StartIndex) <= tolerance)
{
index = candidate - 1;
}
else if (candidate < list.Count - 1 &&
Math.Abs(list[candidate + 1].StartIndex - item.StartIndex) <= tolerance)
{
index = candidate + 1;
}
else
{
// Do whatever you need to in the failure case
}
}
// By now, index is correct
int index=list.BinarySearch(项);
如果(指数<0)
{
int-candidate=~索引;
如果(候选项>0&&
Math.Abs(列表[candidate-1].StartIndex-item.StartIndex)若要执行二进制搜索,列表需要排序,但您不必在任何地方进行排序。@OP:为什么不调整开始索引和结束索引以将其包含在第一位?若要执行二进制搜索,列表需要排序,但您不必在任何地方进行排序。@OP:为什么不调整开始索引和结束索引以包含这些索引首先?