Arrays.binarySearch用法


int[] a = new int[]{128,129};
            int pos = Arrays.binarySearch(a,128);
            System.out.println("Pos="+pos);
            pos =  Arrays.binarySearch(a,129);
            System.out.println("Pos="+pos);
           
            int[] b = new int[]{129,128};
              pos = Arrays.binarySearch(b,128);
            System.out.println("Pos="+pos);
            pos =  Arrays.binarySearch(b,129);
            System.out.println("Pos="+pos);
执行结果为:
Pos=0
Pos=1
Pos=-1
Pos=0

使用二进制搜索算法来搜索指定的 int 型数组,以获得指定的值。必须在进行此调用之前对数组进行排序(sort 方法)。如果没有对数组进行排序,则结果是不明确的。如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。


binarySearch()方法提供了多种重载形式,用于满足各种类型数组的查找需要,binarySearch()有两种参数类型


注:此法为二分搜索法,故查询前需要用sort()方法将数组排序,如果数组没有排序,则结果是不确定的,另外


如果数组中含有多个指定值的元素,则无法保证找到的是哪一个。


⑴.binarySearch(object[ ], object key);


如果key在数组中,则返回搜索值的索引;否则返回-1或者"-"(插入点)。插入点是索引键将要插入数组的那一点,即第一个大于该键的元素索引。


eg:




package Number;
import java.util.Arrays;
public class IntFunction
{
public static void main (String []args)
{
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarySearch(a, 5);
int x2 = Arrays.binarySearch(a, 4);
int x3 = Arrays.binarySearch(a, 0);
int x4 = Arrays.binarySearch(a, 10);
System.out.println("x1:" + x1 + ", x2:" + x2);
System.out.println("x3:" + x3 + ", x4:" + x4);
}
}
/*输出结果:
x1:-4, x2:2
x3:-1, x4:-7
*/




1.不存在时由1开始计数;
2.存在时由0开始计数。


⑵.binarySearch(object[ ], int fromIndex, int endIndex, object key);


如果要搜索的元素key在指定的范围内,则返回搜索键的索引;否则返回-1或者"-"(插入点)。


eg:


1.该搜索键在范围内,但不在数组中,由1开始计数;


2.该搜索键在范围内,且在数组中,由0开始计数;


3.该搜索键不在范围内,且小于范围内元素,由1开始计数;


4.该搜索键不在范围内,且大于范围内元素,返回-(endIndex + 1);(特列)


eg:




package Number;
import java.util.Arrays;
public class IntFunction
{
public static void main (String []args)
{
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarySearch(a, 1, 4, 5);
int x2 = Arrays.binarySearch(a, 1, 4, 4);
int x3 = Arrays.binarySearch(a, 1, 4, 2);
int x4 = Arrays.binarySearch(a, 1, 3, 10);
System.out.println("x1:" + x1 + ", x2:" + x2);
System.out.println("x3:" + x3 + ", x4:" + x4);
}
}
/*输出结果:
x1:-4, x2:2
x3:-2, x4:-4
*/



  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值