C语言解答:有13个单词从小到大存入二维字符数组,用折半查找法找此单词“hello”,找到的话输出该单词和位置,找不到则输出“无此单词”。例如给定char words[][10]={"apple","balloon","disc","english","finish","girl","hello","link","pink","queen","rest","train","umbrella"};
时间: 2023-06-08 09:05:24 浏览: 166
ChitGPT:
好的,让我来解答这个问题。首先,我会用折半查找法来查找单词"hello"在二维字符数组中的位置。以下是代码示例:
```
#include <stdio.h>
#include <string.h>
char words[][10] = {"apple","balloon","disc","english","finish","girl","hello","link","pink","queen","rest","train","umbrella"};
int length = 13;
int binarySearch(char arr[][10], int l, int r, char* x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (strcmp(arr[mid], x) == 0)
return mid;
if (strcmp(arr[mid], x) > 0)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main() {
char word[] = "hello";
int index = binarySearch(words, 0, length - 1, word);
if (index != -1) {
printf("单词 %s 位于第 %d 个位置\n", word, index);
} else {
printf("无此单词\n");
}
return 0;
}
```
输出结果为:
```
单词 hello 位于第 6 个位置
```
希望能够解决您的问题,如果您还有其他问题,请继续提问。
阅读全文