用C 代码实现在有13个单词从小到大存入二维字符数组,用折半法找出单词特定单词
时间: 2023-06-08 18:05:49 浏览: 94
的下标位置。
好的,我明白了。以下是实现该功能的C代码:
```
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 13
#define MAX_WORD_LEN 20
int binarySearch(char words[][MAX_WORD_LEN], int start, int end, char* target) {
while (start <= end) {
int mid = start + (end - start) / 2;
int cmp = strcmp(words[mid], target);
if (cmp == 0) {
return mid;
} else if (cmp < 0) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
int main() {
char words[MAX_WORDS][MAX_WORD_LEN] = {"apple", "banana", "cat", "dog", "elephant", "fox", "grape", "hello", "ice", "jelly", "kite", "lion", "monkey"};
// sort the words in ascending order
for (int i = 0; i < MAX_WORDS - 1; i++) {
for (int j = i + 1; j < MAX_WORDS; j++) {
if (strcmp(words[i], words[j]) > 0) {
char temp[MAX_WORD_LEN];
strcpy(temp, words[i]);
strcpy(words[i], words[j]);
strcpy(words[j], temp);
}
}
}
// binary search for a target word "elephant"
char* target = "elephant";
int index = binarySearch(words, 0, MAX_WORDS - 1, target);
if (index >= 0) {
printf("The index of \"%s\" is %d\n", target, index);
} else {
printf("Target word \"%s\" not found\n", target);
}
return 0;
}
```
运行该程序会输出:
```
The index of "elephant" is 4
```
说明在存有13个单词的二维字符数组中,单词"elephant"的下标位置为4。
阅读全文