二分查找_实现思路、步骤演示、常见问题
前提:有序的int数组
实现思路:
- 判断数组是否为空,为空返回-1
- 定义左边界 0
- 定义右边界 数组长度-1
- 定义中间索引m m=0
- 创建循环 while(左<= 右)
- 给M重新赋值 m=(左+右)>>> 1
- 进行判断
如果arr[m]=要找的数
直接返回m
如果arr[m] > 要找的数
就把右边界变成M+1
如果arr[m] < 要找的数
就把左边界变成M-1 - 异常返回-1
步骤演示:
public class Demo2 {
public static void main(String[] args) {
int[] arr=new int[]{
1,2,3,4,5,6,7,8,9};
int c=2;
int i = test(arr, c);
System.out.println(i);
}
public static int test