因此,为了后代,包括我自己,因为我再次需要 .net 中的NavigableMap。 BinarySearch 适用于 SortedList<TKey, TValue> 的扩展方法和适用于任何 IList<T> 的重载。
public static class BinarySearch4All
{
public static int BinarySearch<TKey, TValue>(this SortedList<TKey, TValue> sortedList,
TKey value, IComparer<TKey> comparer = null)
{
return BinarySearch(sortedList, 0, sortedList.Count, value, comparer);
}
public static int BinarySearch<TKey, TValue>(this SortedList<TKey, TValue> sortedList,
int index, int length, TKey value, IComparer<TKey> comparer = null)
{
return BinarySearch(sortedList.Keys, index, length, value, comparer);
}
public static int BinarySearch<T>(this IList<T> list, T value, IComparer<T> comparer = null)
{
return BinarySearch(list, 0, list.Count, value, comparer);
}
// algorithm courtesy of http://referencesource.microsoft.com/#mscorlib/system/collections/generic/arraysorthelper.cs#114ea99d8baee1be
public static int BinarySearch<T>(this IList<T> list, int index, int length,
T value, IComparer<T> comparer = null)
{
if (comparer == null)
comparer = Comparer<T>.Default;
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order = comparer.Compare(list[i], value);
if (order == 0) return i;
if (order < 0)
lo = i + 1;
else
hi = i - 1;
}
return ~lo;
}
}
注意我想知道为什么 .net 中没有 IRandomAccess<T>,至少 IList<T> 和数组会从中派生出来。
SortedList<TKey, TValue> 实际上可以派生自 IRandomAccess<TKey>,以及 IRandomAccess<TValue> 和 IRandomAccess<KeyValuePair<TKey, TValue>>。