二分法在顺序排列的字典中查找单词(二分)
生活随笔
收集整理的這篇文章主要介紹了
二分法在顺序排列的字典中查找单词(二分)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用二分法在順序排列的字典中查找單詞
typedef struct{ char word[20];/*單詞名*/int count; /*單詞計數器*/}KeyTab; KeyTab tab[M];
若找到,該單詞計數器增1;若沒找到,字典新增一個單詞
根據題意自己寫的代碼,有可能有些錯誤,大家借鑒著看一下吧。
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define inf 0x3f3f3f3f #define M 1010typedef struct{char word[20];int count; }KeyTab; KeyTab tab[M];int main() {int i;for(i=0;i<M;i++) tab[i].count=0,memset(tab[i].word,'\0',sizeof(tab[i].word));//初始化char s[20];int cnt=0;//單詞計數 printf("請依次輸入單詞\n");while(1){scanf("%s",s);if(strcmp(s,"#")==0) break;if(cnt==0) tab[0].count++,strcpy(tab[0].word,s),cnt++;else{int l=0,r=cnt-1,mid,pos;while(l<=r)//二分{mid=l+r>>1;if(strcmp(tab[mid].word,s)<0) l=mid+1;else if(strcmp(tab[mid].word,s)>0) r=mid-1;else break;}if(strcmp(tab[mid].word,s)==0) tab[mid].count++;else{for(i=cnt;i>l;i--) tab[i]=tab[i-1];strcpy(tab[l].word,s);tab[l].count=1;cnt++;}}}for(i=0;i<cnt;i++) printf("%s %d\n",tab[i].word,tab[i].count);return 0; }主要是對二分法和結構體的考察。
努力加油a啊,(o)/~
總結
以上是生活随笔為你收集整理的二分法在顺序排列的字典中查找单词(二分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Educational Codeforc
- 下一篇: 消息称苹果下周将在欧盟为其移动支付系统作