二分查找,元素存在则返回元素,不存在则返回-1
代码:
int BinarySearch( int A[],int n,int x )
{int left=0;
int right =n-1;
while(left<=right)
{
int middle =(left+right)/2;
if((A[middle])==x )return A[middle];
if (A[middle]<x) left=middle+1;
else right=middle -1;
}
return -1;
}
int main()
{ int s[10]={1,2,3,4,5,6,7,8,9,10};
int k=BinarySearch(s,10,5);
cout<<k<<endl;
return 0;
}