使用 Array.BinarySearch() 返回第一个值 <= 查找值?
我正在尝试创建一个“查找”列,该列将返回等于或小于正在查找的值的数组值的索引。这是我的尝试,看起来效果很好,但我想知道是否有更干净的方法?
// 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;
}
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,我认为这是一个非常好的方法。
我唯一可能改变的是使其成为数组的扩展方法,而不是引用类变量的私有函数。然后它就变得通用/不依赖于一个类,并且语法也更清晰:
ranges.GetIndex(...)
像这样的东西:
当然,你必须记住这只适用于已排序的数组...
Nope, I think this is a pretty good approach.
The only thing I might change is to make it an extension method on arrays, instead of a private function referring to a class variable. Then it becomes general / not tied to one class, and the syntax is cleaner too:
ranges.GetIndex(...)
Something like this:
Of course, you'll have to remember this only works on sorted arrays...
您可以使用普通的 for 循环(假设您的数据是有序的)。不确定它是否更干净,但对于大量数据肯定没有那么有效。就我个人而言,我会选择你拥有的 BinarySearch。
You could use a normal for loop (assuming your data is ordered). Not sure if it's cleaner, but certainly not as effective on lots of data. Personally I would go for the BinarySearch you have.