Java开发中经典的小实例-(二分法)

时间:2021-09-10 05:52:42
public int binarySearch(int[] data,int aim){//以int数组为例,aim为需要查找的数
int start = 0;
int end = data.length-1;
int mid = (start+end)/2;//a
while(data[mid]!=aim&&end>start){//如果data[mid]等于aim则死循环,所以排除
if(data[mid]>aim){
end = mid-1;
}else if(data[mid]<aim){
start = mid+1;
}
mid = (start+end)/2;//b,注意a,b
}
return (data[mid]!=aim)?-1:mid;//返回结果
 
 
 
----------------------------------------------------------------------------------------------------------------
 
//针对已经排序好的数组进行查找(对上面代码进行的改进)
publicstaticbooleanbinarySearch(int[]array,inttarget){
intleft=0;
intright=array.length-1;
intmid=(left+right)/2;
while(array[mid]!=target&&right>left){
if(array[mid]>target){
right=mid-1;
}
elseif(array[mid]<target){
left=mid+1;
}
mid=(left+right)/2;
//判断在缩小范围后,新的left或者right是否会将target排除
if(array[right]<target){
break;//若缩小后right比target小,即target不在数组中
}
elseif(array[left]>target){
break;//若缩小后left比target大,即target不在数组中
}
}
return(array[mid]==target);
}