二分搜索算法(折半查找)原理以及递归(recuition),迭代(iteration)的两种实现源代码 ...

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

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值