二分法查找
a是查找的数组,二分法查找的前提条件是a数据的排序是有序的。key是待查找的变量,n是数组a的长度。
int binary( int *a, int &key, int n )
{
int left = 0, right = n - 1, mid = 0;
mid = ( left + right ) / 2;
while( left < right && a[mid] != key )
{
if( a[mid] < key )
left = mid + 1;
else if( a[mid] > key )
right = mid - 1;
mid = ( left + right ) / 2;
}
if( a[mid] == key ) return mid;
return -1;
}