package find;
public class 二分法查找{
public static void main(String[] args) {
int[] a = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int loc;
for( int i=1; i<=a.length; i++){
loc = BinarySearch( a , i );
System.out.println(loc);
}
}
public static int BinarySearch( int[] arr, int aim ){
int head, tail, mid, NotFound=-1;
head = 1; tail = arr.length;
while( head <= tail ){
mid = (head + tail)/2;
//数组取值取不到arr[0],先判断aim=arr[0]
if( aim == arr[0] ){
return 1;
}else{
if( arr[mid] < aim ){
head = mid + 1;
}else if( arr[mid] > aim ){
tail = mid - 1;
}else{
return mid+1; //返回元素在第几个,不是返回数组下标
}
}
}
return NotFound;
}
}
简单二分法查找
最新推荐文章于 2022-10-19 22:47:30 发布