二进制搜索SortedList <K,V>的键

Nit*_*tax 16 c# performance search sortedlist

我需要为线性插值编写一些代码,并且我试图找出一种最有效的方法来搜索一个SortedList<K, V>用于围绕我的目标键的上下键的键.

SortedList<int, double> xyTable = new SortedList<int, double>()
{
    {1, 10}, {2, 20}, {3, 30}, {4,40}
};

double targetX = 3.5;
Run Code Online (Sandbox Code Playgroud)

搜索列表并确定3.5介于3和4之间的最有效方法是什么?我有一个适用于整数的方法/作弊(暂时将目标密钥插入列表然后找到索引)但我想我会问专业人员所以我可以生成高质量的代码.

谢谢.

Col*_*inE 8

二进制搜索在列表中为您提供了不错的性能.但是,Keys属性SortedList是类型IList,而是BinarySearch定义List.幸运的是,您可以IList在此相关问题中找到二进制搜索的实现:

如何在IList <T>上执行二进制搜索?

  • 这是我最喜欢的答案:)应该已经建立在SortedList上。 (2认同)

dod*_*der 5

在我的情况下,源SortedList没有太大变化,因为它被用作查找表.所以在这种情况下,转换SortedList为List<T>一次是有意义的.之后使用内置的BinarySearch方法很容易List<T>...

double targetX = 3.5;

// Assume keys are doubles, may need to convert to doubles if required here.
// The below line should only be performed sparingly as it is an O(n) operation.
// In my case I only do this once, as the list is unchanging.
List<double> keys = xyTable.Keys.ToList();

int ipos = keys.BinarySearch(targetX);

if (ipos >= 0)
{
    // exact target found at position "ipos"
}
else
{
    // Exact key not found: BinarySearch returns negative when the 
    // exact target is not found, which is the bitwise complement 
    // of the next index in the list larger than the target.
    ipos = ~ipos;
    if (ipos >= 0 && ipos < keys.Count)
    {
        if (ipos > 0)
        {
            // target is between positions "ipos-1" and "ipos"
        }
        else
        {
            // target is below position "ipos"
        }
    }
    else
    {
        // target is above position "ipos"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Downvoted,因为有人要求二进制搜索对性能感兴趣.然而,`ToList`是一个多余且缓慢的O(n)操作,性能(CPU和内存消耗)更好地直接在`IList <K> Keys`上工作,如[ColinE的答案]所示(http:/ /stackoverflow.com/a/6101989/709537),它还链接到[复制并粘贴答案]的问题(http://stackoverflow.com/a/2948872/709537). (5认同)