`
zhaohaolin
  • 浏览: 986565 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

二分查找算法分析实现

阅读更多

 

二分查找又称折半查找,它是一种效率较高的查找方法。

  【二分查找要求】:1.必须采用顺序存储结构 2.必须按关键字大小有序排列。
【优缺点】折半查找法的优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
算法思想】首先,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
算法复杂度】假设其数组长度为n,其算法复杂度为o(log(n))
下面提供一段二分查找实现的伪代码:
BinarySearch(max,min,des)
mid-<(max+min)/2
while(min<=max)
mid=(min+max)/2
if mid=des then
return mid
elseif mid >des then
max=mid-1
else
min=mid+1
return max 
折半查找法也称为二分查找法,它充分利用了元素间的次序关系,采用分治策略,可在最坏的情况下 用O(log n)完成搜索任务。它的基本思想是,将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法终止。如 果x<a[n/2],则我们只要在数组a的左半部继续搜索x(这里假设数组元素呈升序排列)。如果x>a[n/2],则我们只要在数组a的右 半部继续搜索x。

 

public class BinarySearch {

	public static void main(String[] args) {
		int[] ints = { 2, 23, 53, 64, 158, 221, 260, 278, 651, 1564, 2355 };
		System.out.println("the position is:"
				+ new BinarySearch().find(ints, 651));
	}

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

}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics