1.思路
对于已经排好序的序列,先与中间位置的元素比较,如果相同则找到;如果小于中间值,则说明在小的区间中,否则说明在大的区间中
2.代码
public static void main(String[] args) {
int[] a = {12,43,65,78,95,234};
int ret = binarySearch(a, 43);
System.out.println(ret);
}
public static int binarySearch(int[] a, int b)
{
int min = 0;
int max = a.length-1;
while(min<=max)
{
int mid = (min+max)>>1;
if(a[mid]==b)
return mid;
else if(a[mid]>b)
max = mid-1;
else
min = mid+1;
}
return -1;
}