折半查找

#include <iostream>
using namespace std;
int search(int key)
{
 int i;
 int a[150];
 for(i=0;i<150;i++)
 {
        a[i]=i;
 }
 int low=0,high=149,mid;
 while(low<=high)
 {
         mid=(low+high)/2;
 
  if(a[mid]==key)
  {
   return mid;
  }
  else
      if(a[mid]<key)
       low=mid+1;
   else
   high=mid-1;
 }
    return 0;
}
int main()
{
 int a,num;
 cout<<"输入要查找的数1-150"<<endl;
 cin>>a;
 num=search(a);
 if(num==0)
 {
     cout<<"您输入的数不存在"<<endl;
 }
 else
 cout<<a<<""<<num<<""<<endl;
 return 0;
}

原文出自开源中国;

posted @ 2014-11-23 12:03  刘阳|lyang|yangakw  阅读(138)  评论(0编辑  收藏  举报