一、二分法查找 Arrays.binarySearch(int a[],int key)
方法1、
public static int binarySearch(int[] a, int key) {
return binarySearch0(a, 0, a.length, key);
}
方法2、
public static int binarySearch(int[] a, int fromIndex, int toIndex,
int key) {
rangeCheck(a.length, fromIndex, toIndex);
return binarySearch0(a, fromIndex, toIndex, key);
}
方法3、
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
由上述源码可以看到方法1和方法2都是都用调用方法3完成查找操作,而方法1和2的区别在于,方法1不需要用户指定fromIndex和toIndex,因此不必进行reangeCheck操作。而方法2则反之。
主要来看方法3,方法3的查找前提是目标数组已经是排过序的,否则将出现无法预知的结果。。
在查找时,主要通过fromIndex和toIndex两个指针的和右移(即/2)一步一步二分法查找key值,当while循环结束之后,意味着并没有找到key,此时并非返回-1,而是返回-(low+1),low为while循环中最后一次的low值。
二、Arrays.equals(int a[],int a2[]);
public static boolean equals(int[] a, int[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i])
return false;
return true;
}
由上述源码可以看到,在比较两个数组时,首先判断两个数组引用是否指向同一个内存地址。若是则相等。
反之,则判断是a与a2是否存在null引用,若有,则不相等。(注意,当两个都为null并不是相等!!)
接着在长度相等的情况下,一次比较数组元素,进行判断