//定义三个变量,保存数组中最小,最大,中间索引
int min = 0;
int max = arr.length-1;
int mid = 0;
//循环折半,条件小索引<=大索引
while(min <= max){
//计算中间索引
mid = (min+max)/2;
//关键字和中间索引,进行比较
if(key > arr[mid]){
min = mid + 1;
}else if( key < arr[mid]){
max = mid -1;
}else{
//找到了,返回索引
return mid;
} |
|