當前位置:成語大全網 - 新華字典 - 求大神解答壹道C語言題:用二分法在順序排列的字典中查找單詞

求大神解答壹道C語言題:用二分法在順序排列的字典中查找單詞

#include <stdio.h>

#include <string.h>

void binary_search(char key[100], char a[100][100], int n) /*自定義函數binary_search*/

{

int low, high, mid, count = 0, count1 = 0;

low = 0;

high = n - 1;

while (low < high) /*當查找範圍不為0時執行循環體語句*/

{

count++; /*count記錄查找次數*/

mid = (low + high) / 2; /*求出中間位置*/

if (strcmp(key,a[mid])<0) /*當key小於中間值*/

high = mid - 1; /*確定左子表範圍*/

else if (strcmp(key,a[mid])>0) /*當key大於中間值*/

low = mid + 1; /*確定右子表範圍*/

else if (strcmp(key,a[mid])==0) /*當key等於中間值證明查找成功*/

{

printf("success!\nsearch %d times!a[%d]=%d", count, mid, key);

/*輸出查找次數及所查找元素在數組中的位置*/

count1++; /*count1記錄查找成功次數*/

break;

}

}

if (count1 == 0) /*判斷是否查找失敗*/

printf("no found!"); /*查找失敗輸出no found*/

}

main()

{

char key[100],a[100][100];

int i,n;

printf("please input the length of array:\n");

scanf("%d", &n); /*輸入單詞個數*/

printf("please input the element:\n");

for (i = 0; i < n; i++)

scanf("%s", a[i]); /*輸入有序單詞到數組a中*/

printf("please input the number which do you want to search:\n");

scanf("%s", key); /*輸入要查找的關鍵字*/

binary_search(key, a, n); /*調用自定義函數*/

}