简体   繁体   English

为什么 binarySearch 方法不返回正确的结果?

[英]why doesn't binarySearch method return the correct result?

Recently I am working on arrays in Java and I needed to use the method binarySearch(arr, v) in Arrays class to search the index of value v in the array arr if found.最近我正在研究 Java 中的数组,我需要使用 Arrays 类中的方法binarySearch(arr, v)来搜索数组arr中值v的索引(如果找到)。

Then I do some tests with some different arrays.然后我用一些不同的数组做一些测试。 When I try to search value 4 in the array {4, 3, 2, 1} I found -5 .当我尝试在数组{4, 3, 2, 1}搜索值4{4, 3, 2, 1}我找到了-5

Would someone can explain that please ?有人可以解释一下吗?

You can check here http://tpcg.io/kibBmw你可以在这里查看http://tpcg.io/kibBmw

The code is below:代码如下:

int[] arr   = {4, 3, 2, 1};
System.out.println(Arrays.binarySearch(arr, 4));

-5 -5

You should do Arrays.sort(arr);你应该做Arrays.sort(arr); before the binary search.在二分查找之前。 From the documentation for Arrays.binarySearch :来自Arrays.binarySearch的文档:

Searches the specified array of ints for the specified value using the binary search algorithm.使用二进制搜索算法在指定的整数数组中搜索指定值。 The array must be sorted (as by the sort(int[]) method) prior to making this call.在进行此调用之前,必须对数组进行排序(如通过 sort(int[]) 方法)。 If it is not sorted, the results are undefined.如果未排序,则结果未定义。

Just look at thejavadoc .只需查看javadoc You need to have a sorted array to use this method.您需要有一个已排序的数组才能使用此方法。 You can do the following:您可以执行以下操作:

Arrays.sort(arr);
Arrays.binarySearch(arr, 4)

对于使用标准二分搜索算法,您的输入数组必须按递增值顺序排列,否则您会得到意想不到的结果。

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

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