//Data为要查找的数组,x为待查找数据值,beg为查找范围起始,last为查找范围终止
//非递归法
int BinarySearch1(int data[], const int x, int beg, int last)
{
int mid;
if (beg > last)
return -1;
while(beg <= last)
{
mid = (beg + last) / 2;
if (x == data[mid] )
return mid;
else if (data[mid] < x)
beg = mid + 1;
else if (data[mid] > x)
last = mid - 1;
}
return -1;
}
//递归法
int BinarySearch2(int data[], const int x, int beg, int last)
{
int mid = -1;
mid = (beg + last) / 2;
if (x == data[mid])
return mid;
else if (x < data[mid])
return BinarySearch2(data, x, beg, mid - 1);
else if (x > data[mid])
return BinarySearch2(data, x, mid + 1, last);
return -1;
}
11-14