BinarySearch太慢了

时间:2014-04-22 15:44:00

标签: c# .net 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;
    }
}

我的二元搜索方法:

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;
    }
}

1 个答案:

答案 0 :(得分:7)

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

MyList.Keys.ToList().BinarySearch(unSearchFor);