C# List.BinarySearch 在未找到值时返回值
当该项目不存在时,我对 List
的 BinarySearch 方法感到困惑。
正如预期的那样,
List<long> theList = {1, 3, 5, ...}.
theList.BInarySearch(0)
返回 0,theList.BInarySearch(3)
返回 1。
但是,theList.BinarySearch(1)
返回-2,而不是我期望的-1。 MSDN 手册说: "返回值:如果找到 item,则为已排序 List 中 item 的从零开始的索引;否则,返回一个负数,该负数是大于 item 的下一个元素的索引的按位补码,或者如果没有更大的元素元素,Count 的按位求补。”
“按位补”?我在这里缺少什么以及为什么是 theList.BinarySearch(1) != -1
?
I am confused about the BinarySearch method of List<T>
in case when the item does not exist.
I've got
List<long> theList = {1, 3, 5, ...}.
theList.BInarySearch(0)
returns 0, and theList.BInarySearch(3)
returns 1, as expected.
However, theList.BinarySearch(1)
returns -2, and not -1 as I'd expect. The MSDN manual says:
"Return value: The zero-based index of item in the sorted List, if item is found; 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."
A "bitwise complement"? What Am I missing here and why is it that theList.BinarySearch(1) != -1
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设您正在谈论
theList.BinarySearch(2)
,因为1
存在并且返回值应为0
。按位补运算符不会产生与对整数求反相同的效果,我认为这是你困惑的根源。无论如何,您不需要了解运算符如何工作即可准确地在搜索结果上进行分支;您问题中的 MSDN 段落以及
~~a = a
直接暗示了以下代码段:I assume you are talking about
theList.BinarySearch(2)
, because1
exists and the return value should be0
.The bitwise complement operator does not produce the same effect as negating the integer, which I think is the source of your confusion. In any case, you do not need to understand how the operator works to accurately branch on the search-result; the MSDN paragraph in your question, and the fact that
~~a = a
, directly implies this snippet:首先-为什么你会期望-1?如果该项目是第一项,则无法返回
-0
(对于整数),因此按理说第二项将返回 -2。接下来,您可以使用
~-2
(按位非运算符)轻松获得正确的索引。First - why would you expect -1? If the item is the first item, it cannot return
-0
(for integers), so it stands to reason -2 will be returned for the second item.Next, you can easily get the right index by using
~-2
- the bitwise not operator.返回这些负索引的原因是为了支持插入列表中未找到的项目。在此示例中,将在索引 = 2 处插入 2。否则,您将必须执行另一个二分搜索才能找到该位置。
The reason for returning these negative indices is to support inserting items that are not found into the list. In this example, 2 would be inserted at index = 2. Otherwise, you would have to perform another binary search to find that position.
要将其转换为插入点,请取按位补码,即:
~retval
To transform it to an insertion point, take the bitwise complement, that is:
~retval