简介
二分查找:在有序不重复值的数组时,每次查找可将范围缩小一半。并且选择这个范围的中点处作为新的猜测值。
示例代码
public class ArrayTest {
private static int findIndex(int[] array, int searchValue) {
//初始下标,初始值为0;
int initIndex = 0;
//最大下标,初始值为数组长度-1
int maxIndex = array.length - 1;
//二分查找值
int midIndex;
//查找次数统计
int num = 0;
//遍历
while (true) {
num++;
//初始化二分查找值
midIndex = (maxIndex + initIndex) / 2;
//判断相等,则返回下标。
if (array[midIndex] == searchValue) {
System.out.println("查找次数:" + num + "次;");
return midIndex;
//判断初始值大于最大值时,则查询完成,未找到查询值
} else if (initIndex > maxIndex) {
System.out.println("查找次数:" + num + "次;");
return -1;
} else {
//二分查找值大于查找值,将二分查找值下标-1赋值给最大值。
if (array[midIndex] > searchValue) {
maxIndex = midIndex - 1;
//否则,将二分查找值+1赋值给初始值。
} else {
initIndex = midIndex + 1;
}
}
}
}
public static void main(String[] args) {
//初始数组,实现二分查找需要数组为有序数组。
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//定义查找值
int searchValue = 9;
//调用查找方法
int indexValue = ArrayTest.findIndex(array, searchValue);
if (indexValue == -1) {
System.out.println("未查询到值:" + searchValue);
} else {
System.out.println("查询到值:" + array[indexValue]);
}
}
}