java - 在 int 数组中搜索

标签 java arrays binary-search

我正在尝试使用 Arrays.binarySearch() 搜索 int 数组中的值,并且我知道如果值可以在数组中找到,则此方法返回值的索引号,如果数组没有找到include value 方法返回负数。

这是我的数组:

int[] searchInArray=new int[6];
searchInArray = new int[]{2,3,4,22,1,2};

这是我的代码:

int result1=Arrays.binarySearch(searchInArray,55);
int result2=Arrays.binarySearch(searchInArray, 22);

当我运行此代码时,我得到 return1=-7 和 return2=-7。

然后我尝试找到 1 而不是 22,然后 result2 为“-1”。

我哪里出错了?

最佳答案

使用binarySearch()的前提是数组必须是有序的。你的不是。

引自the javadoc :

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. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

(强调我的)

关于java - 在 int 数组中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271536/

相关文章:

perl - 如何扩展二进制搜索迭代器以使用多个目标

algorithm - 使用分而治之是否会提高在数组中查找最大值和最小值的时间复杂度

java - Spring AOP 自定义注解

python - 从多维 numpy 数组中选择

java - 使正弦图移动

c - 使用 char** 数组作为结构成员加载/填充结构,c

Java:声明一叠牌的最佳方式

java - 对对象数组进行二分查找以查找元素的字段

java - 检查数组中的多个值

java - 借助 BeanShell 调用嵌入代码中的方法