BinarySearch太慢了

use*_*426 0 .net c# performance binary-search

怎么可能当我在SortedList上使用.net BinarySearch时,它需要的时间比我在同一个列表上使用我自己的二进制搜索方法要长得多?

使用.net binarysearch:

int ipos = MyList.Keys.ToList().BinarySearch(unSearchFor);

if (ipos >= 0)
{
    // exact target found at position "ipos"
    return MyList[unSearchFor];
}
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;
    try
    {
        return MyList.Values[ipos - 1];
    }
    catch
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的二元搜索方法:

int nStart = 0;
int nEnd = MyList.Count - 1;
int mid = 0;

while (nStart <= nEnd)
{
    mid = nStart + (nEnd - nStart) / 2;
    uint unCurrKey = MyList.Values[mid].Key;

    if (unSearchFor == unCurrKey)
        return MyList.Values[mid];

    if (unSearchFor < unCurrKey)
    {
        nEnd = mid - 1;
    }
    else
    {
        nStart = mid + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ham*_*hid 7

是不是因为你在下面的列表中调用BinarySearch()时你正在做.ToList()?

MyList.Keys.ToList().BinarySearch(unSearchFor);
Run Code Online (Sandbox Code Playgroud)

  • 不知道你为什么得到-1.第一种算法是O(n),其中适当的二进制搜索是O(log n).您肯定在示例中找到了一个会严重影响性能的算法错误. (3认同)