• JAVA之数组查询binarySearch()方法详解


    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
    */


  • 相关阅读:
    vue 跨域访问http
    vue 生命周期小结
    koa的教程
    spoj104 HIGH
    loj2026 「JLOI / SHOI2016」成绩比较
    loj2024「JLOI / SHOI2016」侦查守卫
    loj2016 「SCOI2016」美味
    loj2014 「SCOI2016」萌萌哒
    loj2013 「SCOI2016」幸运数字
    loj2012 「SCOI2016」背单词
  • 原文地址:https://www.cnblogs.com/riskyer/p/3249183.html
Copyright © 2020-2023  润新知