2010-08-15 102 views
5

在項目不存在的情況下,我對於List<T>的BinarySearch方法感到困惑。C#List <T> .BinarySearch當值沒有找到時返回值

我有

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

theList.BInarySearch(0)返回0,和theList.BInarySearch(3)返回1,符合市場預期。

但是,theList.BinarySearch(1)返回-2,而不是-1,如我所料。 MSDN手冊中說: 「返回值:如果找到項目,則排序列表中的項目的從零開始的索引;否則,爲負值,它是大於項目的下一個元素的索引的按位補數或,如果沒有更大的元素,Count的逐位補碼「。

「按位補碼」?我在這裏錯過了什麼,爲什麼它是theList.BinarySearch(1) != -1

+0

我想你正在尋找'theList.BinarySearch(2)'? 「1」就在那裏...... – Kobi 2010-08-15 09:25:15

+0

按位補碼只是一個數字,它是第一個數字每個位的補碼。 00110101 =〜11001010.這就像一個不操作,但在哪裏!做一個布爾值不是整個值,〜做一個不在每個位上。 – 2010-08-15 12:48:03

回答

4

首先 - 爲什麼你會想到-1?如果該項目是第一個項目,它不能返回-0(整數),所以它的原因-2將返回第二個項目。

接下來,您可以通過使用~-2 - 按位非運算符輕鬆獲得正確的索引。

1

要將其轉換爲一個插入點,走位補,那就是:~retval

7

我假設你說的是theList.BinarySearch(2),因爲1存在,返回值應該是0

bitwise complement operator不會產生與否定整數相同的效果,我認爲這是造成混淆的根源。無論如何,您無需瞭解運營商如何在搜索結果上準確分支;在MSDN段落你的問題,而事實上,~~a = a,直接意味着這個片段:

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

退貨的原因這些負面指標是支持插入未發現到列表中的項目。在這個例子中,2將被插入在索引= 2處。否則,你將不得不執行另一個二分搜索來找到那個位置。

+0

有趣的是,我想知道什麼是使用該按位補碼...在文檔中的解釋是相當晦澀 – 2010-08-15 11:36:49