将上面代码改成动态输入
时间: 2023-12-10 18:04:50 浏览: 27
改为动态输入的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXL 100 //定义表中最多记录个数
typedef int KeyType;
typedef char InfoType[10];
typedef struct {
KeyType key; //KeyType为关键字的数据类型
InfoType data; //其它数据
} NodeType;
typedef NodeType SeqList[MAXL]; //顺序表类型
int BinSearch(SeqList R, int n, KeyType k) { //二分查找算法
int low = 0, high = n - 1, mid, count = 0;
while (low <= high) {
mid = (low + high) / 2;
printf(" 第%d次比较:在[%d,%d]中比较元素R[%d]:%d\n",++count,low,high,mid,R[mid].key);
if (R[mid].key == k) //查找成功返回
return mid;
if (R[mid].key > k) //继续在R[low..mid-1]中查找
high = mid - 1;
else //继续在R[mid+1..high]中查找
low = mid + 1;
}
return -1;
}
int main() {
SeqList R;
KeyType k;
int i, n;
printf("请输入要查找的元素个数n:");
scanf("%d", &n);
printf("请输入%d个元素:\n", n);
for (i = 0; i < n; i++) //建立顺序表
scanf("%d", &R[i].key);
printf("关键字序列:");
for (i = 0; i < n; i++)
printf("%d ", R[i].key);
printf("\n");
printf("请输入要查找的元素k:");
scanf("%d", &k);
printf("查找%d的比较过程如下:\n", k);
if ((i = BinSearch(R, n, k)) != -1)
printf("元素%d的位置是%d\n", k, i);
else
printf("元素%d不在表中\n", k);
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)