How to perform a binary search on IList?

前端 未结 11 1377
执念已碎
执念已碎 2020-11-28 09:32

Simple question - given an IList how do you perform a binary search without writing the method yourself and without copying the data to a type with bui

11条回答
  •  庸人自扰
    2020-11-28 10:32

    I doubt there is a general purpose binary search method in .NET like that, except for the one being present in some base classes (but apparently not in the interfaces), so here's my general purpose one.

    public static Int32 BinarySearchIndexOf(this IList list, T value, IComparer comparer = null)
    {
        if (list == null)
            throw new ArgumentNullException(nameof(list));
    
        comparer = comparer ?? Comparer.Default;
    
        Int32 lower = 0;
        Int32 upper = list.Count - 1;
    
        while (lower <= upper)
        {
            Int32 middle = lower + (upper - lower) / 2;
            Int32 comparisonResult = comparer.Compare(value, list[middle]);
            if (comparisonResult == 0)
                return middle;
            else if (comparisonResult < 0)
                upper = middle - 1;
            else
                lower = middle + 1;
        }
    
        return ~lower;
    }
    

    This of course assumes that the list in question is already sorted, according to the same rules that the comparer will use.

提交回复
热议问题