当输入包含重复项时 java.util.Arrays.binarySearch() 的结果
Result of java.util.Arrays.binarySearch() when input contains duplicates
一般都是自己写二分查找函数。现在我尝试使用 java.util.Arrays 提供的内置函数。我发现了一些我无法解释的奇怪现象。有人可以帮忙吗?
考虑以下代码片段:
1. int[] a = {5, 7, 7, 8, 8, 8, 10};
2. System.out.println(Arrays.binarySearch(a, 8));
3. System.out.println(Arrays.binarySearch(a, 0, 7, 8));
4. System.out.println(Arrays.binarySearch(a, 0, 6, 8));
5. int[] a2 = {5, 7, 7, 8, 8, 10};
6. System.out.println(Arrays.binarySearch(a2, 8));
第 2 行和第 3 行的输出是 3,这是我预期的(下限)。
但是第 4 行和第 6 行的输出是 4!!!...
我搜索了 Java 文档 https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#binarySearch-int:A-int- 但没有找到任何关于此的答案。
来自文档:
Searches a range of the specified array of ints for the specified
value using the binary search algorithm. The range must be sorted (as
by the sort(int[], int, int) method) prior to making this call. If it
is not sorted, the results are undefined. If the range contains
multiple elements with the specified value, there is no guarantee
which one will be found.
方法 returns 您要搜索的元素的索引,并且来自 docs,
If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
一般都是自己写二分查找函数。现在我尝试使用 java.util.Arrays 提供的内置函数。我发现了一些我无法解释的奇怪现象。有人可以帮忙吗?
考虑以下代码片段:
1. int[] a = {5, 7, 7, 8, 8, 8, 10};
2. System.out.println(Arrays.binarySearch(a, 8));
3. System.out.println(Arrays.binarySearch(a, 0, 7, 8));
4. System.out.println(Arrays.binarySearch(a, 0, 6, 8));
5. int[] a2 = {5, 7, 7, 8, 8, 10};
6. System.out.println(Arrays.binarySearch(a2, 8));
第 2 行和第 3 行的输出是 3,这是我预期的(下限)。
但是第 4 行和第 6 行的输出是 4!!!...
我搜索了 Java 文档 https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#binarySearch-int:A-int- 但没有找到任何关于此的答案。
来自文档:
Searches a range of the specified array of ints for the specified value using the binary search algorithm. The range must be sorted (as by the sort(int[], int, int) method) prior to making this call. If it is not sorted, the results are undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.
方法 returns 您要搜索的元素的索引,并且来自 docs,
If the array contains multiple elements with the specified value, there is no guarantee which one will be found.