二分法查找的要求是数组或者集合的元素必须是有序的
示例代码如下:
package com.dinglit;
/***
* 二分查找的数组或者集合必须是有序的
*
* @author liuhuanchao
* @date 2019-06-30
*/
public class BinarySearchTest {
public static void main(String[] args) {
// 目标数组
int[] arr = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
testBinarySearch(arr);
}
private static void testBinarySearch(int[] arr) {
// 目标值
int targetValue = 2;
// 开始下标
int beignIndex = 0;
// 结束下标
int endIndex = arr.length - 1;
// 数组中间位置下标
int midIndex = (beignIndex + endIndex) / 2;
// 目标位置下标
int targetIndex = -1;
while (true) {
// 如果查询目标值在数组中不存在,退出执行,防止死循环
if (endIndex <= beignIndex) {
break;
}
if (arr[midIndex] == targetValue) {
targetIndex = midIndex;
break;
} else {
// 判断目标值是否比数组中间值大
if (targetValue > arr[midIndex]) {
// 将开始位置调整到中间位置后的一个位置
beignIndex = midIndex + 1;
} else {
// 将结束位置调整到中间位置前的一个位置
endIndex = midIndex - 1;
}
}
// 重新计算中间下标
midIndex = (beignIndex + endIndex) / 2;
}
System.out.println("目标值在数组arr的下标是:" + targetIndex);
}
}