分治与递归策略_二分搜索法

二分搜索是运用分治策略的典型例子

二分搜索方法充分利用了元素间的次序关系,采用分治策略,可在最坏情况下用O(logn)
的时间完成搜索任务。
 
看看下面的程序


#include "iostream.h"
#include "iomanip.h"

#define max 100

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

void main()
{
 int map[max] = { 1 , 2 , 4 , 5 , 7 , 8 };
 int n = 6;
 int x;

 int i;
 cout<<"数列:"<<endl;
 for( i = 0 ; i < n ; i++ )
  cout<<setw(5)<<map[i];
 cout<<endl;

 x = 3;
 int order = BinarySearch( map , x , n );

 if( order > 0 )
 {
  cout<<"指定数 "<<x<<" 处于第 "<<order+1<<" 位"<<endl;
 }
 else
 {
  cout<<"没有找到指定数 "<<x<<endl;
 }
}

其实在c语言库函数中已经有bsearch()了,
利用它可以更方便地解决二分查找问题。

#include "stdlib.h"

void*  bsearch (
 const void * key, //待查找单元的关键字
 const void * base,  //在什么地方找
 size_t num,   //有多少单元可以查找
 size_t width,   //每个单元占多少字节
 int (*fncompare)(const void *, const void * )  //怎样比较两个元素大小
 );

//程序举例

#include "iostream.h"
#include "iomanip.h"
#include "stdlib.h"  //注意这里

#define max 100

int cmp( const void *a , const void *b )
{
 int x = *(int*)a;
 int y = *(int*)b;
 return x - y;
}

void main()
{
 int map[max];
 int n = 10;
 int key;
 int *item;
 int i;

 for( i = 0 ; i < n ; i++ )
 {
  map[i] = i * i + 3 * i + 4;
 }

 cout<<"数列:"<<endl;
 for( i = 0 ; i < n ; i++ )
  cout<<setw(5)<<map[i];
 cout<<endl;

 key = 44;
 item = (int*)bsearch( &key , map , n , sizeof(int) , cmp );

 if( item != NULL )
 {
  cout<<"指定数 "<<*item<<" 在数列中"<<endl;
 }
 else
 {
  cout<<"找不到指定数 "<<*item<<endl;
 }
}
//
// 详细介绍可以到
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_bsearch.asp


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值