Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4130
  • 博文数量: 3
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 34
  • 用 户 组: 普通用户
  • 注册时间: 2014-12-29 19:48
文章分类
文章存档

2015年(2)

2014年(1)

我的朋友
最近访客

分类: C/C++

2015-02-23 19:50:25


点击(此处)折叠或打开

  1. //二分查找
  2. #include<bits/stdc++.h>
  3. using namespace std;

  4. int n;
  5. int binary_search(int a[],int x)
  6. {
  7.     int low,high;
  8.     int mid;
  9.     low = 1;
  10.     high = n;
  11.     while(low<=high)
  12.     {
  13.         mid=(low+high)/2;
  14.         if(a[mid]==x)
  15.         {
  16.             return mid;
  17.         }    
  18.         else if(a[mid]>x)
  19.         {
  20.             high=mid-1;
  21.         }
  22.         else low=mid+1;
  23.     }
  24.     return 0;
  25. }
  26. int main()
  27. {
  28.     int a[1000];
  29.     cout<<"input the size of the array:\t";
  30.     cin>>n;
  31.     int i,j,k;
  32.     int x;
  33.     cout<<"input the elements:"<<endl;
  34.     for(i=1;i<=n;i++)
  35.         cin>>a[i];
  36.     cout<<"input the number what you want to find in the array:\t";
  37.     cin>>x;
  38.     int is_find;
  39.     is_find=binary_search(a,x);
  40.     if(is_find)
  41.         printf("find it at the index of %d in the array\n",is_find);
  42.        else
  43.         cout<<"not found"<<endl;    
  44. }


阅读(198) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~