折半查找(细节的指出)
代码:
public int binarySearch(int key, int[] array) {
int low = 0;
int high = array.length - 1;
while(low <= high) {
int mid = low + (high - low) / 2;
if(key == array[mid])
return mid;
if(key < array[mid])
high = mid - 1;
else
low = mid + 1;
}
return -low - 1;//为避免0的存在,如果找不到返回的值为要插入的位置的负值-1,-1是因为避免0的存在
}