简体   繁体   English

二分查找返回负值

[英]Binary Search returns negative values

I have a list of Series and a vertical annotation.我有一个系列列表和一个垂直注释。 I want to have the Y value of the signals for every X position of the vertical annotation (VA).我想要垂直注释 (VA) 的每个 X 位置的信号的 Y 值。

Here is what I have done so far.这是我到目前为止所做的。

VerticalAnnotation VA;                
List<double> Points = new List<double>();

foreach (var sig in Signals)
{
    for (int g = 0; g < sig.Points.Count; g++)
    {
        Points.Add(sig.Points[g].XValue);
    }
    Points.Sort();
}

and

private void chart1_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e)
{
    var x = Points.BinarySearch(VA.X);
}

But for some reason x variable gets negative values which does not make sense.但是由于某种原因, x 变量得到了没有意义的负值。

The docs say this: 文档是这样说的:

Returns ... the zero-based index of item in the sorted List, if item is found;返回 ... 排序列表中 item 的从零开始的索引,如果找到了 item; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count否则,一个负数,它是下一个大于 item 的元素的索引的按位补码,或者,如果没有更大的元素,则为Count 的按位补码

Note that the latter value is also negative.请注意,后一个值也是负数。

A negative result means that what you are looking for is not in the list.否定结果意味着您要查找的内容不在列表中。 Also the result can be used (by inverting it as ~result ) to know where the value at hand would have been found if it had been in the list, or where you would need to insert it to keep the list nicely sorted.同样的结果可以使用(通过翻转它~result )知道在哪里发现手头的值,如果它已经在列表中,或者您需要将其插入到保持列表很好排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM