10.倒转数组
题目:
将长度为n的数组倒转。
解答:
void Reverse(int *data, int n)
{
int i, j;
for(i = 0, j = n - 1; i < j; ++i, --j)
Swap(&data[i], &data[j]);
}
11.二分查找
题目:
写出二分查找。
解答:
下面的代码在查找到目标时返回下标,否则返回-1:
int BinarySearch(const int *data, int len, int x)
{
int left = 0, right = len - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (x < data[mid])
right = mid - 1;
else if (x > data[mid])
left = mid + 1;
else
return mid;
}
return -1;
}
对它稍加改动则得到下面的版本,返回值i保证data[i-1] <= x < data[i]。
int BinarySearch2(const int *data, int len, int x)
{
int left = 0, right = len-1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (x < data[mid])
right = mid - 1;
else
left = mid + 1;
}
return left;
}