import java.util.Arrays;
public class binarySearch { public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int index = binarySearch(arr, 6); System.out.println("这个数对应的索引是 :" + index); // System.out.println(Arrays.binarySearch(arr, 6)); } public static int binarySearch(int[] arr, int zhi) { int qi = 0; //数组起始值 int zhong = arr.length - 1; //数组的末值 int index = -1; //定义一个下标 while (qi <= zhong) { int suoyin = (qi + zhong) / 2; //获取一个中间值得索引; int guess = arr[suoyin]; //中间索引对应的值 if (guess >= zhi) { //中间索引与输入的值比较 zhong = suoyin - 1; //比较后的范围重新定义 } if (guess <= zhi) { qi = suoyin + 1; } if (guess == zhi) { index = suoyin; //相等直接跳出 break; } } return index; //返回索引 }}