程序填空题:二分查找
有15个已经排好序的数存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。
如果该数不在数组中,则输出无此数。请填空。
变量说明:top,bott为查找区间两端点的下标;loca为查找成功与否的开关变量。
```c++
#include
int main(void)
{
int N, number, top, bott, min, loca;
int a[15] = { -3, -1, 0, 1, 2, 4, 6, 7, 8, 9, 12, 19, 21, 23, 50};
N = 15;
scanf("%d", &number);
loca = 0; top = 0; bott = N - 1;
if ((number < a[0]) || (number > a[N - 1]))
loca = -1;
while ((loca == 0) && (top <= bott)) {
min = @@[(top + bott) / 2](2);
if (number == a[min]) {
loca = min;
printf("The serial number is %d\n", loca + 1);
break;
} else if (number < a[min])bott = min - 1;
else @@[top = min + 1](2);
}
if (@@[loca == -1 || top > bott](2))
printf("%d isn't in table\n", number);
return 0;
}
```
答案:
第1空:(top + bott) / 2
第2空:top = min + 1
第3空:loca == -1 || top > bott
如果该数不在数组中,则输出无此数。请填空。
变量说明:top,bott为查找区间两端点的下标;loca为查找成功与否的开关变量。
```c++
#include
int main(void)
{
int N, number, top, bott, min, loca;
int a[15] = { -3, -1, 0, 1, 2, 4, 6, 7, 8, 9, 12, 19, 21, 23, 50};
N = 15;
scanf("%d", &number);
loca = 0; top = 0; bott = N - 1;
if ((number < a[0]) || (number > a[N - 1]))
loca = -1;
while ((loca == 0) && (top <= bott)) {
min = @@[(top + bott) / 2](2);
if (number == a[min]) {
loca = min;
printf("The serial number is %d\n", loca + 1);
break;
} else if (number < a[min])bott = min - 1;
else @@[top = min + 1](2);
}
if (@@[loca == -1 || top > bott](2))
printf("%d isn't in table\n", number);
return 0;
}
```
答案:
第1空:(top + bott) / 2
第2空:top = min + 1
第3空:loca == -1 || top > bott