原理:
基本思想:假设数据是按升序排序的,对于给定值x,从序列的中间位置开始比较,如果当前位置值等于x,则查找成功;若x小于当前位置值,则在数列的前半段中查找;若x大于当前位置值则在数列的后半段中继续查找,直到找到为止。
算法:
假如有一组数为3,12,24,36,55,68,75,88要查给定的值24.可设三个变量front,mid,end分别指向数据的上界,中间和下界,mid=(front+end)/2.
1.开始令front=0(指向3),end=7(指向88),则mid=3(指向36)。因为mid>x,故应在前半段中查找。
2.令新的end=mid-1=2,而front=0不变,则新的mid=1。此时x>mid,故确定应在后半段中查找。
3.令新的front=mid+1=2,而end=2不变,则新的mid=2,此时a[mid]=x,查找成功。
如果要查找的数不是数列中的数,例如x=25,当第三次判断时,x>a[mid],按以上规律,令front=mid+1,即front=3,出现front>end的情况,表示查找不成功。
例:在有序的有N个元素的数组 中查找用户输进去的数据x。
算法如下:
1.确定查找范围front=0,end=N-1,计算中项mid(front+end)/2。
2.若a[mid]=x或front>=end,则结束查找;否则,向下继续。
3.若a[mid]<x,说明待查找的元素值只可能在比中项元素大的范围内,则把 mid+1的值赋给front,并重新计算mid,转去执行步骤2;若a[mid]>x,说明待查找的元素值只可能在比中项元素小的范围内,则把 mid-1的值赋给end,并重新计算mid,转去执行步骤2。
[一维数组,折半查找]
实现:
/**
*
* 一个二分查找法
*
* @author nileader
*/
public class BinaryQuery {
/**
* *折半查找法,又称十分法查找 查找的对象是一个按序排好的数组
*/
public static void main(String[] args) {
int[] initVals = { 9, 12, 37, 53, 67, 71, 89, 122, 290, 435, 555, 888,
1104, 1111, 2222, 3333, 21343, 43256, 56778300 };
for (int i = 0; i < initVals.length; i++) {
System.out.print(initVals[i] + "、");
}
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
int targetVal = cin.nextInt();
BinaryQuery bq = new BinaryQuery();
int postion = bq.query(initVals, targetVal);
if (postion == -1)
System.out.println("没有找到");
else
System.out.println("要查找的数字在数组中的第 " + (postion + 1) + "个位置");
}
}
/*
* @param values 要找的数组对象
*
* @param targetVal 要找的目标数字
*
* @return -1 没有找到,返回-1
*/
public int query(int[] initVals, int targetVal) {
int lowBound = 0;
int upBound = initVals.length - 1;
int nowPostion;
while (true) {
nowPostion = (lowBound + upBound) / 2;
if (initVals[nowPostion] == targetVal) {
return nowPostion;
}
else if (lowBound > upBound)
return -1;
else
if (initVals[nowPostion] < targetVal)
lowBound = nowPostion + 1;
else
upBound = nowPostion - 1;
}
}
}