二分查找的C++实现

1.递归实现

 

  1. #include <iostream>
  2. using std::cout;
  3. using std::cin;
  4. using std::endl;
  5. int BSearch(int *a,int key,int low,int high)
  6. {
  7.     int mid;
  8.     if(low>high)
  9.         return -1;
  10.     mid=(low+high)/2;
  11.     if(key==a[mid])
  12.         return mid;
  13.     if(key<a[mid])
  14.         return BSearch(&a[0],key,low,mid-1);
  15.     if(key>a[mid])
  16.         return BSearch(&a[0],key,mid+1,high);
  17. }
  18. void main()
  19. {
  20.     int key;
  21.     //cout<<"please input the number"<<endl;
  22.     int a[10]={1,2,3,4,5,8,9,10,11,21};
  23.     cout<<"please input the number"<<endl;
  24.     cin>>key;
  25.     cout<<BSearch(&a[0],key,0,9)<<endl;
  26. }

2.非递归实现

  1. #include <iostream>
  2. using std::cout;
  3. using std::cin;
  4. using std::endl;
  5. int BSearch(int *a,int key,int low,int high)
  6. {
  7.     while(low<=high)
  8.     {
  9.         int mid=(low+high)/2;
  10.         if(key==a[mid])
  11.             return mid;
  12.         if(key>a[mid])
  13.         {
  14.             low=mid+1;
  15.         }
  16.         if(key<a[mid])
  17.         {
  18.             high=mid-1;
  19.         }
  20.     }
  21.     return -1;
  22. }
  23. void main()
  24. {
  25.     int key;
  26.     //cout<<"please input the number"<<endl;
  27.     int a[10]={1,2,3,4,5,8,9,10,11,21};
  28.     cout<<"please input the number"<<endl;
  29.     cin>>key;
  30.     cout<<BSearch(&a[0],key,0,9)<<endl;
  31. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值