【问题标题】:C# List<T>.BinarySearch return value when value not foundC# List<T>.BinarySearch 在未找到值时返回值
【发布时间】:2010-08-15 09:10:58
【问题描述】:

如果项目不存在,我对List&lt;T&gt; 的 BinarySearch 方法感到困惑。

我有

List<long> theList = {1, 3, 5, ...}.

theList.BInarySearch(0) 返回 0,theList.BInarySearch(3) 返回 1,正如预期的那样。

但是,theList.BinarySearch(1) 返回 -2,而不是我期望的 -1。 MSDN 手册说: "返回值:如果找到 item,则返回排序 List 中 item 的从零开始的索引;否则,一个负数,它是下一个大于 item 的元素的索引的按位补码,或者,如果没有更大的元素,Count 的按位补码。"

“按位补码”?我在这里错过了什么,为什么theList.BinarySearch(1) != -1

【问题讨论】:

  • 我想您正在搜索theList.BinarySearch(2)1 就在那儿……
  • 按位补码只是一个数字,它是第一个数字的每一位的补码。 00110101 = ~ 11001010。这就像一个非操作,但在哪里!对整个值进行布尔运算,~ 对每一位都进行运算。

标签: c# list generic-list


【解决方案1】:

我假设你在谈论theList.BinarySearch(2),因为1 存在并且返回值应该是0

bitwise complement operator 不会产生与否定整数相同的效果,我认为这是您困惑的根源。在任何情况下,您都不需要了解运算符如何准确地根据搜索结果进行分支;您问题中的 MSDN 段落,以及 ~~a = a 的事实直接暗示了这个 sn-p:

int index = theList.BinarySearch(num);

if (index >= 0)
{
    //exists
    ...
}
else
{
    // doesn't exist
    int indexOfBiggerNeighbour = ~index; //bitwise complement of the return value

    if (indexOfBiggerNeighbour == theList.Count)
    {
        // bigger than all elements
        ...
    }

    else if (indexOfBiggerNeighbour == 0)
    {
        // smaller than all elements
        ...
    }

    else
    {
        // Between 2 elements
        int indexOfSmallerNeighbour = indexOfBiggerNeighbour - 1;
        ...
    }
}

【讨论】:

    【解决方案2】:

    首先 - 你为什么会期望 -1?如果该项是第一项,则无法返回-0(对于整数),所以按理说第二项将返回-2。

    接下来,您可以使用~-2(按位非运算符)轻松获得正确的索引。

    【讨论】:

      【解决方案3】:

      返回这些负索引的原因是为了支持将未找到的项目插入到列表中。在本例中,2 将被插入到 index = 2 处。否则,您将不得不执行另一次二分搜索来找到该位置。

      【讨论】:

      • 有趣,我想知道按位补码有什么用......文档中的解释很模糊
      【解决方案4】:

      要将其转换为插入点,取按位补码,即:~retval

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-03
        • 2014-09-10
        • 1970-01-01
        • 2010-12-26
        • 2014-03-08
        • 2023-01-04
        • 1970-01-01
        • 2011-06-23
        相关资源
        最近更新 更多