qingcheng奕  

#include<iostream>
using namespace std;

int BinarySearch(int a[],int n,int goal)
{
 for(int i=0;i<=n;i++)
 cout<<a[i]<<endl;
 int mid,low=0,high=n;
 while(low<=high)
 {
  mid=(low+high)/2;
  if(goal==a[mid])
   return mid;
  else if(goal<a[mid])
   high=mid-1;
  else
   low=mid+1;
 }
 return -1;
}
int main()
{
 int arr[10]={0,3,7,9,11,35,66,78,89,100};
 int a;
 while(cin>>a)
 {
  int b;
  b=BinarySearch(arr,9,a);
  cout<<b<<endl;
 }
 return 0; 
}

//非递归算法

int BinarySearch()

{

      int low=0,high=n-1;

      int temp;

      while(low<=high)

      {

           temp=(low+high)/2;

           if(k==R[temp])

           {

                 return temp;

           }

           else if(k<R[temp])

           {

                 high=temp-1;

           }

           else

           {

                 low=temp+1;

           }

      }

      return -1;

}

posted on 2011-04-24 17:27  qingcheng奕  阅读(179)  评论(0编辑  收藏  举报