列表已排序。
我有一个列表,我想对它进行二进制搜索。T有StartIndex、EndIndex等成员。
我可以用StartIndex对列表进行二进制搜索,也就是说:我已经为此实现了IComparable。
我需要将其稍微扭曲如下:我想找到一个StartIndex,它可能以较小的值关闭。
例如:T.StartIndex=100
如果输入为101且OffBy 1,则BinarySearch应返回此对象。
我该怎么做?
顺便问一下,我在问如何使用列表中的默认BinarySearch方法。这就是我感兴趣的,而不是自定义二进制搜索实现。

最佳答案

如果使用List<T>.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

10-04 17:04