编写一个C语言程序从键盘输入一整数,然后在一个整型一维数组 a[20]中,用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印”No found”。注意代码中不要出现中文字符
时间: 2024-02-09 16:11:25 浏览: 69
以下是一个用C语言编写的折半查找的程序:
```c
#include <stdio.h>
#define N 20
int binary_search(int a[], int n, int key);
int main()
{
int a[N], i, key, index;
printf("Please enter %d numbers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
printf("Please enter the number you want to find:");
scanf("%d", &key);
index = binary_search(a, N, key);
if (index == -1) {
printf("No found\n");
} else {
printf("%d is the value of the %dth element in the array.\n", key, index + 1);
}
return 0;
}
int binary_search(int a[], int n, int key)
{
int low = 0, high = n - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
return mid;
} else if (a[mid] > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
```
这个程序首先从键盘上读入20个整数,然后通过折半查找的方法查找用户输入的整数key是否在数组a中,并返回该数在数组中的下标。如果该数不在数组中,则输出"No found"。
阅读全文