Arrays类

Arrays

Arrays: java提供了一个类专门针对数组一系列操作的工具类

    public static String toString(int[] a)
    public static void sort(int[] a)
    public static int binarySearch(int[] a,int key)

public class ArraysDemo1 {
    public static void main(String[] args) {
        //传入任意类型元素的一维数组,将其变成一个字符串形式返回
        int[] arr = {11,22,33,44,55};
//        String s1 = Arrays.toString(arr);
        System.out.println(Arrays.toString(arr));


        //public static void sort(int[] a)
        //对除了boolean类型以外的一维数组做排序
        int[] arr2 = {21,31,6,23,78,12,47};
        Arrays.sort(arr2); // 底层是快速排序
        System.out.println(Arrays.toString(arr2));


        //public static int binarySearch(int[] a,int key) 二分查找,前提是被查找的序列是有序的!
        //查找元素key在数组a中的位置
        //[6, 12, 21, 23, 31, 47, 78]
        int index = Arrays.binarySearch(arr2, 4);
        System.out.println(index); // -8  -1

    }
}

Array中的binarySearch方法源码解释

class Arrays{

    //[6, 12, 21, 23, 31, 47, 78]
    //int index = Arrays.binarySearch(arr2, 99);
    public static int binarySearch(int[] a, int key) {
        // a - arr2 - [6, 12, 21, 23, 31, 47, 78]
        // key - 99
        return binarySearch0(a, 0, a.length, key);
    }

    private static int binarySearch0(int[] a, int fromIndex, int toIndex,int key) {
        // a - [6, 12, 21, 23, 31, 47, 78]
        // fromIndex - 0
        // toIndex - 7
        // key - 99
        int low = fromIndex; // 0
        int high = toIndex - 1; // 6

        while (low <= high) {
            int mid = (low + high) >>> 1; // 3  5  6
            int midVal = a[mid]; // 23  47  78

            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. // -8
    }

}
posted @ 2024-10-10 14:44  rrrzzzrrr  阅读(16)  评论(0)    收藏  举报