二分法查找 - Java

原理:

    基本思想:假设数据是按升序排序的,对于给定值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;
		}
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值