【问题标题】:C# Binary Search VariationC# 二分搜索变体
【发布时间】:2010-12-30 17:04:26
【问题描述】:

列表已排序。

我有一个列表,我想对其进行二进制搜索。 T 有 StartIndex、EndIndex 等成员。

我可以使用 StartIndex 对列表进行二进制搜索,即:我为此实现了 IComparable。

我需要稍微扭曲一下,如下所示:我想找到一个可能是 OffBy 小值的 StartIndex。

例如:T.StartIndex= 100

如果输入是 101 并且 OffBy 1 那么 BinarySearch 应该返回这个对象。

我该怎么做?

顺便说一句,我正在询问如何使用 List 具有的默认二进制搜索方法。这就是我感兴趣的,对自定义二分搜索实现不感兴趣。

【问题讨论】:

  • 为了执行二分搜索,需要对列表进行排序,但您不要在任何地方都这样做。
  • @OP:为什么不首先调整开始和结束索引以包含它们?

标签: c# .net algorithm search binary-search


【解决方案1】:

如果您使用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

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 2015-04-13
    • 2021-12-10
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多