sort后fill然后binarySearch

jixixiaofeng 2010-12-04 12:58:47
import java.util.*;

public class TestArray{
public static void main(String[] args){
int[] num = {2,1,3,4,5};
Arrays.sort(num);
Arrays.fill(num,1,2,6);
System.out.println(Arrays.binarySearch(num,6));
}
}
应该显示是几呢?

我想应该是1,可输出是-6.为什么呢?
...全文
59 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
a411416948 2010-12-04
  • 打赏
  • 举报
回复
二分查找必先排序再查找
api原话
使用二分搜索法来搜索指定的 int 型数组,以获得指定的值。必须在进行此调用之前对数组进行排序(通过 sort(int[]) 方法)。如果没有对数组进行排序,则结果是不确定的。如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。

djvfe 2010-12-04
  • 打赏
  • 举报
回复

Arrays.fill(num,1,2,6);是指吧num数组的第二个和第三个元素设置为6,完成后数组长度依然是5
好好看看api啊
qian119110 2010-12-04
  • 打赏
  • 举报
回复
没有排序引起的混乱吧。
Jlins 2010-12-04
  • 打赏
  • 举报
回复
+[Quote=引用 1 楼 goldenfish1919 的回复:]

Java code

int[] num = {2,1,3,4,5};
Arrays.sort(num);
System.out.println(Arrays.toString(num));
Arrays.fill(num,1,2,6);
System.out.println(Arrays.toString(num));
……
[/Quote]
若鱼1919 2010-12-04
  • 打赏
  • 举报
回复

int[] num = {2,1,3,4,5};
Arrays.sort(num);
System.out.println(Arrays.toString(num));
Arrays.fill(num,1,2,6);
System.out.println(Arrays.toString(num));
//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.
System.out.println(Arrays.binarySearch(num,6));

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧