1.概念
通过二分法在已经排好序的数组中查找指定的元素,并返回该元素的下标。
2.使用注意
此法为二分搜索法,故查询前需要用sort()方法将数组排序,如果数组没有排序,则结果是不确定的。如果数组中含有多个指定值的元素,则无法保证找到的是哪一个。
3.返回值
该方法的返回值类型为整型,具体返回值具体分为以下两种情况:
(1)如果数组中存在该元素,则会返回该元素在数组中的下标
(2)如果数组中不存在该元素,则会返回-(插入点 + 1)
这里的插入点具体指的是:如果该数组中存在该元素,那个元素在该数组中的下标
4.实例
public static void main(string[] args) {list<integer> lists = new arraylist<integer>();lists.add(3);lists.add(6);lists.add(8);lists.add(7);lists.add(1);// 原来的集合system.out.println(原来的集合:);for (integer str : lists) {system.out.print(str + );} // 对集合进行排序collections.sort(lists);system.out.println(\n排序后的集合:);for (integer str : lists) {system.out.print(str + );} // 使用binarysearch方法查找集合中的元素int i = collections.binarysearch(lists, 2);system.out.println(\n2所在的位置: + i); }
以上就是binarysearch在java中怎么使用的详细内容。