包装类的数组

Arrays针对于数组做操作的类,该类包含用于操作数组的各种方法(如排序和搜索)。
        public static String toString(int[] a)
        public static void sort(int[] a)//排序
        public static int binarySearch(int[] a,int key)//二分查找
public class ArraysDemo {
    public static void main(String[] args) {
        //定义一个数组
        int[] arr = {21, 32, 44, 1, 4, 89, 16};

        //public static String toString(int[] a)
        //将数组转换成一个字符串
//        System.out.println(arr);
        String s = Arrays.toString(arr);
        System.out.println(s);

        System.out.println("=================================");
        //public static void sort(int[] a)
        Arrays.sort(arr);
        System.out.println("排序后的数组为:" + Arrays.toString(arr));

        System.out.println("=================================");
        //public static int binarySearch(int[] a,int key)
        //[1, 4, 16, 21, 32, 44, 89]
        //二分查找的前提是数组本身是排过序的
        System.out.println("二分查找32:" + Arrays.binarySearch(arr, 32));
        System.out.println("二分查找32:" + Arrays.binarySearch(arr, 100)); // -8



    }
}

-8怎么来的?分析源码

arr:[1, 4, 16, 21, 32, 44, 89]
key:100


public static int binarySearch(int[] a, int key) {
    /*
            a -- arr -- [1, 4, 16, 21, 32, 44, 89]
            key -- 100
            a.length -- 7
    */
    return binarySearch0(a, 0, a.length, key);
}

// Like public version, but without range checks.
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                 int key) {
    /*
        a -- arr -- [1, 4, 16, 21, 32, 44, 89]
        fromIndex -- 0
        toIndex -- 7
        key -- 100
    */

    int low = fromIndex;      // 0
    int high = toIndex - 1;   // 6

    while (low <= high) {
        int mid = (low + high) >>> 1; // 3  5  6
        int midVal = a[mid]; // 21 44 89

        if (midVal < key)
            low = mid + 1; // 4 6 7
        else if (midVal > key)
            high = mid - 1;
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found.    -(7+1) -->  -8

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值