二分搜索算法

来源:互联网 发布:数据分析经理 编辑:程序博客网 时间:2024/04/30 02:18

折半查找法也称为二分查找法,它充分利用了元素间的次序关系,采用分治策略,可在最坏的情况下用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。

二分搜索法的应用极其广泛,而且它的思想易于理解。第一个二分搜索算法早在1946 年就出现了,但是第一个完全正确的二分搜索算法直到1962年才出现。Bentley在他的著作《Writing Correct Programs》中写道,90%的计算机专家不能在2小时内写出完全正确的二分搜索算法。问题的关键在于准确地制定各次查找范围的边界以及终止条件的确定,正确地归纳奇偶数的各种情况,其实整理后可以发现它的具体算法是很直观的。

C++描述

template<class Type> int BinarySearch(Type a[],const Type& x,int n)  {  int left=0; int right=n-1; while(left<=right){  int middle=(left+right)/2; if (x==a[middle]) return middle; if (x>a[middle]) left=middle+1; else right=middle-1; }  return -1; }

 

递归实现(recuition)

template<class Record, class Key> int binary_search( Record * r, const int & low, const int & high, const Key & k ) { int mid = (low + high)/2; if( low < high ) {   if( k <= r[mid] )    binary_search( r, low, mid, k );    else    binary_search( r, mid+1, high, k ); } else if( low == high ) {   if( k == r[mid] )    return low;   else    return -1; } else   return -1; }


迭代实现(iteration)

template<typename Record, typename Key> int binary_search( Record * r, const int & size, const Key & k ) { int low=0, high=size-1, mid; while( low < high ) {   mid = (low + high) / 2;   if( k > r[mid] )    low = mid + 1;   else    high = mid; } if( low > high )   return -1; else {   if( k == r[low] )    return low;   else    return -1; } }



 

原创粉丝点击