找不到密钥时,java.util.Collections.binarySearch return 值背后的原因是什么?
What is the reasoning behind java.util.Collections.binarySearch return value, when the key isn't found?
引用 docs 它说 java.util.Collections.binarySearch(List<? extends Comparable<? super T>> list, T key)
returns...
the index of the search key, if it is contained in the list;
otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list:
the index of the first element greater than the key, or list.size() if
all elements in the list are less than the specified key...
我的问题是,定理 (-(insertion point) - 1)
有什么意义(如果有的话),当找不到键时它是 return 值?为什么不只是 return insertion point
例如?
来自相同的文档,如果密钥存在,return 值必须 >= 0。如果所有元素都大于键,insertion point
可能为零,即使键不存在,也会导致 return 值为零。另一方面,值 (-(insertion point) - 1)
总是小于零。
Note that this guarantees that the return value will be >= 0 if and only if the key is found.
首先,如果没有找到该元素,则必须根据文档return输入负值,否则无法区分找到和未找到。
好的,那为什么不 -insertion point
?想象一下,如果插入点为 0(搜索到的元素小于所有现有元素),那么该逻辑将中断 - not found 将 return 为非负数。因此额外的 -1
.
好的,为什么不总是 -1
?
因为知道排序列表中不匹配项的插入点有助于找到以下问题的答案:
What is the next element that is bigger than the one I ask for?
和
How many elements are larger than the one I (didn't) find?
而且,二分查找的工作方式是,算法在它终止时知道这个索引,所以为什么不在不需要额外费用的情况下共享它呢?
这是一种将两个用例合并到一个方法调用中的方法。 List.indexOf()
和类似的方法会在找不到元素时简单地 return -1,但是 Collections.binarySearch()
更进一步并且 returns 是一个负数,当您重新按元素构建排序列表。
引用 docs 它说 java.util.Collections.binarySearch(List<? extends Comparable<? super T>> list, T key)
returns...
the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key...
我的问题是,定理 (-(insertion point) - 1)
有什么意义(如果有的话),当找不到键时它是 return 值?为什么不只是 return insertion point
例如?
来自相同的文档,如果密钥存在,return 值必须 >= 0。如果所有元素都大于键,insertion point
可能为零,即使键不存在,也会导致 return 值为零。另一方面,值 (-(insertion point) - 1)
总是小于零。
Note that this guarantees that the return value will be >= 0 if and only if the key is found.
首先,如果没有找到该元素,则必须根据文档return输入负值,否则无法区分找到和未找到。
好的,那为什么不 -insertion point
?想象一下,如果插入点为 0(搜索到的元素小于所有现有元素),那么该逻辑将中断 - not found 将 return 为非负数。因此额外的 -1
.
好的,为什么不总是 -1
?
因为知道排序列表中不匹配项的插入点有助于找到以下问题的答案:
What is the next element that is bigger than the one I ask for?
和
How many elements are larger than the one I (didn't) find?
而且,二分查找的工作方式是,算法在它终止时知道这个索引,所以为什么不在不需要额外费用的情况下共享它呢?
这是一种将两个用例合并到一个方法调用中的方法。 List.indexOf()
和类似的方法会在找不到元素时简单地 return -1,但是 Collections.binarySearch()
更进一步并且 returns 是一个负数,当您重新按元素构建排序列表。