java二分法查找
前提:所查找的必须为有序
//二分法查找
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
int dest1 = 6;
int head = 0;//初始索引
int end = arr.length - 1;//初始末索引
boolean isFlag = true;
while (head <= end) {
int middle = (head + end) / 2;
if (dest1 == arr[middle]) {
System.out.println("索引位置:" + middle);
isFlag = false;
break;
} else if (arr[middle] > dest1) {
end = middle - 1;
} else if (arr[middle] < dest1) {
head = middle + 1;
}
}
if (isFlag){
System.out.println("未找到");
}