/*在有序表中进行二分查找*/
#include<iostream>
using namespace std;
int binarySearch(int list[],int key,int arraySize)
{
int low = 0;
int high = arraySize-1;
while(low<=high)
{
int mid = (low+high)/2;
if(key<list[mid])
high=mid-1;
else if(key>list[mid])
low=mid+1;
else
return mid;
}
return -1;
}
int main()
{
int key,*a,n,locat;
cout<<"input the size of the array:"<<endl;
cin>>n;
a=new int[n]; //动态分配数组大小
cout << "input the numbers of the array:"<<endl;
for(int i=0;i<n;i++) //输入数组元素
cin>>a[i];
cout<<"input the number you want to search: "<<endl;
cin >>key;
locat=binarySearch(a,key,n);
if(locat!=-1)
cout<<"the location of the number is:"<<locat+1<<endl;
else
cout <<"the number you want to search isn't exist in the array"<<endl;
return 0;
}