2009-12-29 100 views
0

該列表已分類。C#二進制搜索變化

我有一個列表,我想對它進行二分搜索。 T有像StartIndex,EndIndex等成員

我可以用StartIndex在列表上進行二分搜索,即:我已經爲此實現了IComparable。

我需要扭轉這一點,如下所示:我想找到一個StartIndex可能OffBy一個小值。

例如:T.StartIndex = 100

如果輸入是101和OffBy 1然後BinarySearch的應返回該對象。

我該怎麼做?

順便說一句,我問如何與默認的二進制搜索方法列表有。這是我感興趣的,對定製的二分查找實現不感興趣。

+0

爲了執行二進制搜索,列表需要進行排序,但你在任何地方不mantion說。 – 2009-12-29 07:33:47

+0

我剛剛做過...... – DarthVader 2009-12-29 07:35:11

+0

是啊米奇......前4個單詞。 – mpen 2009-12-29 07:46:19

回答

6

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

我會買。謝謝。 – DarthVader 2009-12-29 07:47:20