输出顺序表{1,2,3,4,5,6,7,8,9,10}中采用折半查找法查找关键字9的过程 C语言完整代码
时间: 2023-08-13 14:04:53 浏览: 88
下面是一个示例代码,实现了在顺序表中采用折半查找法查找关键字的过程:
```c
#include <stdio.h>
#define MAXSIZE 10
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
int BinarySearch(SqList L, int key);
int main() {
SqList list = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, MAXSIZE};
int index = BinarySearch(list, 9);
printf("The index of key 9 is %d\n", index);
return 0;
}
int BinarySearch(SqList L, int key) {
int low = 0;
int high = L.length - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (L.data[mid] == key) {
return mid;
} else if (L.data[mid] > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
```
运行结果为:
```
The index of key 9 is 8
```
说明在顺序表中成功找到了关键字9,并返回其索引位置8。
阅读全文