二分查找
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int value = 2;
int left = 0;
int right = arr.length-1;
int mid = (left + right)/2;
int index = -1;
//退出循环:(1)找到了 value == arr[mid] break;
// (2)没找到,全部都找完了 left > right
while(left <= right){
if(value == arr[mid]){//找到了
index = mid;
break;
}else if(value > arr[mid]){//value在arr[mid]的右边
left = mid + 1;//修改左边界,使得mid往右移动
}else if(value < arr[mid]){//value在arr[mid]的左边
right = mid - 1;//修改右边界,使得mid往左边移动
}
mid = (left + right)/2;
}
if(index == -1){
System.out.println(value + "在数组中不存在!");
}else{
System.out.println(value + "在数组中的下标是" + index);
}