所以在這裏是爲了後代,包括我自己,因爲我還需要在.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;
}
}
N.B.我想知道爲什麼在.net中沒有IRandomAccess<T>
,至少有IList<T>
和數組可以從中得到。
SortedList<TKey, TValue>
實際上可以從IRandomAccess<TKey>
以及IRandomAccess<TValue>
和IRandomAccess<KeyValuePair<TKey, TValue>>
得出。
其非常奇怪List有二進制搜索,但SortedList沒有二分搜索。 – 2017-09-22 21:06:43