1

我正在尝试创建一个“查找”列,该列将返回等于或小于正在查找的值的数组值的索引。所以这是我的尝试,它似乎工作正常,但我想知道是否有更清洁的方法?

// Sorted
float[] ranges = new float[]
  {
     0.8f,
     1.1f,
     2.7f,
     3.9f,
     4.5f,
     5.1f,
  };


private int GetIndex(float lookupValue)
{
    int position = Array.BinarySearch(ranges, lookupValue);
    if (position < 0)
    {
        // Find the highest available value that does not
        // exceed the value being looked up.
        position = ~position - 1;
    }

    // If position is still negative => all values in array 
    // are greater than lookupValue, return 0
    return position < 0 ? 0 : position;
}

谢谢。

4

2 回答 2

3

不,我认为这是一个很好的方法。

我唯一可能改变的是使其成为数组的扩展方法,而不是引用类变量的私有函数。然后它变得通用/不依赖于一个类,并且语法也更清晰:ranges.GetIndex(...)

像这样的东西:

public static class Extensions
{
    public static int GetIndex<T>(this T[] ranges, T lookupValue)
    {
        // your code here
    }
}

当然,您必须记住这仅适用于排序数组...

于 2010-08-10T20:04:58.223 回答
1

您可以使用普通的 for 循环(假设您的数据是有序的)。不确定它是否更干净,但在大量数据上肯定没有那么有效。就我个人而言,我会选择您拥有的 BinarySearch。

int GetIndex(IList<float> ranges, float target)
{
    for (int i = 0; i < ranges.Count; i++)
    {
        if(ranges[i] < target) continue;
        if (ranges[i] >= target) return i;
    }
    return 0;
}
于 2010-08-10T20:09:39.257 回答