#include <iostream>
using namespace std;
int main()
{int binary_search(int*a,int n,int x);
int n=10;
int p=6;
int q;
int sorted_array[n]={1,2,3,4,5,6,7,8,9,10};
q=binary_search(sorted_array,n,p);
if (q==-1)
cout<<"Not Found"<<endl;
else
cout<<"idx="<<q+1<<endl;
return 0;
}
int binary_search(int*a,int n,int x)
{int low=0;
int high=n-1;
int mid;
while(low<=high)
{
if(a[low]==x)
return (low);
if(a[high]==x)
return (high);
mid=low+(high-low)/2;
if(a[mid]==x)
return (mid);
if(a[mid]<x)
low=mid+1;
else
high=mid-1;
}
if(low>high)
return (-1);
}
网友评论