public class BinarySearch
{
public static void main(String[]args)
{
int arr[]=new int[]{1,2,3,4,5,6,7,8,9,10};
System.out.println(binSearch(arr,10));
}
public static int binSearch(int[]arr,int target)
{
int mid;
int first=0;
int last=arr.length-1;//当last=arr.length-1时循环控制应为first<=last
while(first<=last)
{
mid=first+((last-first)>>1);//避免数据溢出
if(target==arr[mid])
{
return mid;
}
else if(target>arr[mid])
{
first=mid+1;
}
else
{
last=mid-1;//易错点
}
}
return -1;
}
}
二分法(数组形式)
最新推荐文章于 2024-01-28 14:53:03 发布