【二分查找法】

public int find(int[] a,int searchKey){
	int nElems = a.length;
	if(nElems<1)
		return nElems;
	
	int lowerBound = 0;
	int upperBound = nElems-1;
	int curIn;
	while(true){
		curIn = (lowerBound+upperBound)/2;
		if(a[curIn]==searchKey)
			return curIn;
		else if(lowerBound>upperBound)
			return nElems;
		else{
			if(a[curIn]<searchKey)
				lowerBound = curIn+1;
			else
				upperBound = curIn-1;
		}
	}
}

在数据量较大时,较适合使用二分查找法。使用二分查找法的前提,数组必须是有序的,因此如果数组无序,要先对数组进行排序。

二分查找法的主要思想是:

1、获取数组长度nElems,进而得到中间位置curIn,a[curIn]便是数组中间位置的值。

2、拿要进行查找的值与中间位置值a[curIn]进行比较,如若相等,返回这个位置curIn,如果不等,进而将区间二分,获得一个新的范围,继续二分查找。

3、当上边界lowerBound大于下边界upperBound时,说明数组中没有这个要查找的值,返回数组长度。


本文首次发表依鹏csdn博客,转载注明出处http://blog.csdn.net/m0_37240709/article/details/78038296

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值