public static String toString(int[] a) {
if (a == null) //如果a的值是null
return "null"; //返回"null"
int iMax = a.length - 1; //iMax是最大索引
if (iMax == -1) //数组中没有元素
return "[]"; //返回"[]"
StringBuilder b = new StringBuilder(); //创建字符串缓冲区
b.append('['); //添加[
for (int i = 0; ; i++) { //遍历数组中元素,没写判断条件,系统默认是true
b.append(a[i]); //添加数组中的元素
if (i == iMax) //如果i是最大索引
return b.append(']').toString(); //添加],把StringBuffer对象转换称字符串并返回
b.append(", "); //添加", "
}
}
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) { //传入实际参数(a,0,a.length,key)
int low = fromIndex; //min = 0
int high = toIndex - 1; //max = a.length - 1
while (low <= high) { //如果 min <= max 则进入循环
int mid = (low + high) >>> 1; //mid = (min + max) / 2 (>>> 1 无符号右移1位,相当于/2)
int midVal = a[mid]; //取出中间索引处的值
if (midVal < key) //如果中间索引处的值小于要找的值
low = mid + 1; //min = mid + 1
else if (midVal > key) //如果中间索引处的值大于要找的值
high = mid - 1; //max = mid - 1
else //如果midVal = key
return mid; // key found //返回mid
}
return -(low + 1); // key not found. //如果 min > max,返回 -(min + 1)
}
|
|