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; // 6while (low <= high) {
int mid = (low + high) >>> 1; // 3 5 6
int midVal = a[mid]; // 21 44 89if (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}