二分查找实现
1.调用Arrays中的binarySearch方法即可实现
【使用前提:数组必须为升序排列】
public class Demo1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//查找元素定为4
int key = 4;
int index1 = Arrays.binarySearch(arr, 4);
//3
System.out.println("对应的索引为:"+index1);
int index2 = Arrays.binarySearch(arr, 11);
//-11查找的元素不存在,返回的则是(-插入点-1)
//插入点:如果这个元素在数组中,它应该在哪个索引上
//-1是防止元素为0不存在,索引返回0,为了避免则-1
System.out.println("对应的索引为:"+index2);
}
}
打印结果:
-----------------------------------------------------
对应的索引为:3
对应的索引为:-11
2.其底层代码实现逻辑为:
【使用前提:数组必须为有序排列,下面为升序版,如果为降序则将start和end做替换】
public class Demo1 {
public static void main(String[] args) {
int []arr ={1,2,3,4,5,6,7,8,9,10};
//查找元素定为4
int key =4;
//定义初始和结尾索引
int index = getbinarySerach(arr, key);
//对反回值做判断
if(index!=-1){
System.out.println(key+"对应的索引为"+index);
}else {
System.out.println("该数组中没有该元素");
}
}
private static int getbinarySerach(int[] arr, int key) {
int start =0;
int end =arr.length-1,mid;
//循环判断mid的值
while (start<=end) {
mid =(end+start)>>1;
if(arr[mid]<key){
start =mid +1;
}else if(arr[mid]>key){
end =mid -1;
}else {
return mid;
}
}
return -1;
}
}