1. 首先编辑一组数据, 和待查找的数据
注: 二分查找最好是先排序, 这里是升序排序
数组中有可能有多个相同数据, 所以创建一个集合用来存放已经找到的索引
将参数传进方法内, 接下来实现方法:
public static void main(String[] args) {
int[] arr = {1,2,3,3,3,6,8};
Arrays.sort(arr);
System.out.println("首先排序: " + Arrays.toString(arr));
Scanner input = new Scanner(System.in);
System.out.println("请输入要查找的数: ");
int a = input.nextInt();
List<Integer> list = new ArrayList<>();
List<Integer> list1 = binarySearch(arr,a,0,arr.length-1, list);
//返回的集合为null或者集合长度为0就说明没有找到
if (list1 != null && list1.size() != 0){
System.out.println("索引值: " + list1);
}else {
System.out.println("没有这个数");
}
}