二分查找

好程序員訓練營

<A href="http://www.goodprogrammer.org/" target="blank">ios培訓</A>

------我的c語言筆記,期待與您交流! 

#include<stdio.h>

#include<string.h>

#include<ctype.h>


#define MAXWORD 100

#define BUFSIZE 100

#define NKEYS (sizeof keytab/sizeof keytab[0])


char buf[BUFSIZE];

int bufp=0;


struct key

{

    char *word;

    int count;

}keytab[]={

    {"auto",0},{"break",0},{"case",0},{"char",0},{"const",0},{"continue",0},{"default",0},/* ...*/ ,{"unsigned",0},{"void",0},{"volatile",0},{"while",0}

};


struct key

{

char *word;

int count;

}tab;


int getword(char *,int);

struct key *binsearch(char *,struct key *,int);


/*取回一個字符(可能是壓回的字符)*/

int getch(void)

{

    return (bufp>0) ? buf[--bufp]:getchar();

}


/*把字符壓回到輸入中*/

void ungetch(int c)

{

    if(bufp >= BUFSIZE)

        printf("ungetch: too many characters\n");

    else

buf[bufp++]=c;

}


/*getword函數:從輸入中讀取下一個單詞或字符*/

int getword(char *word,int lim)

{

    int c,getch(void);

    void ungetch(int);

    char *w=word;


    while(isspace(c=getch()));

       if(c!=EOF)

   *w++=c;

    if(!isalpha(c))

    { 

        *w='\0';

        return c;

    }

    for(;--lim>0;w++)

       if(!isalnum(*w=getch()))

       {

            ungetch(*w);

    break;

        }

    *w='\0';

    return word[0];

}


/*binsearch函數:在tab[0]到tab[n-1]中查找單詞(折半查找函數)*/


struct key *binsearch(char *word,struct key *tab,int n)

{

   int cond;

   struct key *low=&tab[0];

   struct key *high=&tab[n];

   struct key *mid;


   while(low<high)

   {

        mid=low+(high-low)/2;

        if((cond=strcmp(word,mid->word))<0)

            high=mid;

else if(cond>0)

            low=mid+1;

        else

            return mid;

   }

   return NULL;

}


/*統計關鍵字出現的次數:採用指針方式實現的版本*/

int main()

{

    char word[MAXWORD];

    struct key *p;


    while(getword(word,MAXWORD)!=EOF)

       if(isalpha(word[0]))

          if((p=binsearch(word,keytab,NKEYS))!=NULL)

             p->count++;

    for(p=keytab;p<keytab+NKEYS;p++)

       if(p->count>0)

          printf("%4d %s\n",p->count,p->word);

    return 0;

}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章