.net - SortedList.IndexOfKey(key) 返回 item.key >= key 的项目的索引

标签 .net sortedlist

如果键不在列表中,SortedList.IndexOfKey(key) 返回 -1。

这是否意味着如果我想在列表中找到大于或等于键的键的索引,我必须自己实现二分搜索?还是我忽略了一些开箱即用的东西?

我当然想得到 O(log(n)) 的结果,所以请不要使用 LINQ 迭代和过滤魔法。

(一般来说,我想要像 Java 的 NavigableMap 功能这样的功能,即在排序的 map /字典上进行高效迭代等功能,但就目前而言,上述问题的答案就足够了,我可以按照自己的方式“扩展方法”从那里以某种方式)

最佳答案

所以,为了后代,包括我自己,我再次需要一个 NavigableMap在.net中。 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;
    }
}

注意我想知道为什么没有 IRandomAccess<T>在 .net 中,至少 IList<T>和数组将派生自。
SortedList<TKey, TValue>实际上可以源自 IRandomAccess<TKey> ,以及 IRandomAccess<TValue>IRandomAccess<KeyValuePair<TKey, TValue>> .

关于.net - SortedList.IndexOfKey(key) 返回 item.key >= key 的项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9030246/

相关文章:

c# - 如何检查是否在 Mock 对象上调用了特定的属性 setter ?

c# - 在 C# 中自动实现的属性默认值

c# - 现有连接被远程主机强制关闭

c# - Azure Cosmos DB 通过 C# 代码将集合 TTL 设置为 - on(无默认值)

c# - 在 .Net 中实现优先级数组集合的最快(插入速度)方法是什么?

c# - 从排序列表中加权随机选择

c# - C# SortedList<TKey, TValue>.Keys.Contains 方法抛出 null 异常是一件好事吗?

c# - 为什么接口(interface)在 IL 级别作为 "abstract interface"发出?

java - 如何在 android 中从 Arraylist 日期按降序对日期进行排序?

python - 如何找到可以将新项目插入排序列表并保持排序的索引?