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
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.