1.确定查找范围front=0,end=N-1,计算中项mid=(front+end)/2。
2.若a[mid]=x或front>=end,则结束查找;否则,向下继续。
public class BubbleTest {
/**
* 利用二分法查询数据所在位置,如果查找失败返回-1
* @param array
* @param value
* @return
*/
public static int binarySearch(int[] array, int value) {
int front = 0;
int end = array.length - 1;
int mid =(front + end) / 2;
while (front <= end) {
if (value == array[mid]) {
return mid;
}
if (value < array[mid]) {
end = mid - 1;
mid=(front + end) / 2;
}
if (value > array[mid]) {
front = mid + 1;
mid=(front + end) / 2;
}
}
return -1;
}
public static void main(String[] args) {
int[] a = { 3, 12, 24, 36, 55, 68, 75, 88 };
int result = BubbleTest.binarySearch(a, 66);
System.out.println("输出数字24所在位置 " + result);
}
}