算法:二分法查找/折半查找
/
//查找算法
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