public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
//目标值
int userNumber = 70;
//调用方法,返回索引,没有返回-1
int numberIndex = getBinarySearch(arr, userNumber);
System.out.println("值在数组中索引是:" + numberIndex);
}
/**
* //二分查找方法,返回索引,没有返回-1
* @param arr
* @param userNumber
* @return
*/
private static int getBinarySearch(int[] arr, int userNumber) {
//开始索引
int startIndex = 0;
//结束索引
int endIndex = arr.length - 1;
//判断是否存在(开始索引<=结束索引)
while (startIndex <= endIndex) {
//中间索引 = (开始+结束)÷2
int midIndex = (endIndex + startIndex) / 2;
//如果(中间索引位置元素>目标值)
if (arr[midIndex] > userNumber) {
//修改结束索引 = 中间索引 - 1
endIndex = midIndex - 1;
} else if (arr[midIndex] < userNumber) {
startIndex = midIndex + 1;
} else {
//否则 返回索引
return midIndex;
}
}
//没有返回-1
return -1;
}
原文:https://www.cnblogs.com/saoge/p/13596089.html