在数组a 中用折半查找法查找一个数,若找到显示其在数组中的位置。若找不到提示“No found!”。要求编写自定义函数 int srch(int all,int x,int left,int right)函数,该函数用折半查找法在数组a 中指定的下标范围内left 和right 之间查找x,若找到,返回数组所在的下标,否则返回-1。
#include <iostream>
using namespace std;
// 自定义函数 int srch(int all, int x, int left, int right)
int srch(int all, int x, int left, int right)
{
// 当左边界大于右边界时,说明没有找到该数
while (left <= right)
{
// 计算中间位置
int mid = (left + right) / 2;
// 当找到该数时,返回它所在的下标
if (all[mid] == x) {
return mid;
}
// 当该数在右半边时,缩小查找范围
else if (all[mid] < x) {
left = mid + 1;
}
// 当该数在左半边时,缩小查找范围
else {
right = mid - 1;
}
}
// 没有找到该数,返回-1
return -1;
}
int main()
{
// 定义数组
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int n = sizeof(a) / sizeof(a[0]); // 数组长度
// 定义要查找的数
int x = 5;
// 查找数的下标
int index = srch(a, x, 0, n - 1);
// 判断是否找到该数,如果没有,输出 "No found!";如果找到,输出该数在数组中的位置
if (index == -1) {
cout << "No found!" << endl;
}
else {
cout << "The position of " << x << " in the array is " << index << endl;
}
return 0;
}