1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <stdio.h> #include <string.h> int bin_search(char *w, char dic[][4], int n) { int low = 0, high = n - 1, mid, result; while (low <= high) { mid = (low + high) / 2; result = strcmp(w, dic[mid]); if (result < 0) high = mid - 1; else if (result > 0) low = mid + 1; else return mid; } return -1; } void main() { char dictionary[26 * 26 * 26][4]; for (int i = 0; i < 26; i++) for (int j = 0; j < 26; j++) for (int k = 0; k < 26; k++) sprintf(dictionary[i * 26 * 26 + j * 26 + k], "%c%c%c", 'a' + i, 'a' + j, 'a' + k); int pos; char word[4]; printf("word: "); scanf("%3s", word); pos = bin_search(word, dictionary, 26 * 26 * 26); if (pos == -1) printf("[%s] is not exists.\n", word); else printf("[%s] is %d page.\n", word, pos + 1); }