java基础二分法查找

时间:2022-03-14 00:32:19

算法:二分法查找/折半查找

/java基础二分法查找

//查找算法
static int search(int[] arr,int key){
int low=0;
int height=arr.length-1;

while(low<=height){
System.out.println(low+"^^^"+height);
int mid=(low+height)>>1;
if(key>arr[mid])//猜小了
{
low=mid+1;
}
else if(key<arr[mid])
{
height=mid-1;
}
else{
return mid;
}
}
return -1;
}

//主程序
public class Demo {
public static void main(String[] args){
int[] arr=new int[]{0,1,2,3,4,5,6,7,8,9};
int a=search(arr,8);
System.out.println(a);
}

}
运行结果是:

0^^^9
5^^^9
7^^^9
8