新聞中心

        EEPW首頁 > 嵌入式系統 > 設計應用 > 快速排序+二分查找與哈希表

        快速排序+二分查找與哈希表

        作者: 時間:2016-11-28 來源:網絡 收藏
        快速序排+二分查找

        #include
        const int MAX= 100001;
        typedef struct
        {
        char e[11];
        char f[11];
        }Entry;
        Entry entry[MAX];
        int i = 0;//詞典總條數

        int cmp(const void *a, const void *b)
        {
        return strcmp((*(Entry *)a).f, (*(Entry *)b).f);
        }

        int BinSearch(char c[])
        {
        int low = 0, high = i - 1;
        int mid, t;
        while(low <= high)
        {
        mid = (low + high) / 2;
        t = strcmp(entry[mid].f, c);
        if(t == 0)
        return mid;
        else if(t == -1)
        low = mid + 1;
        else
        high = mid - 1;
        }
        return -1;
        }

        int main()
        {
        char str[25];
        int index = -1;
        while(gets(str))
        {
        if(str[0] == )
        break;
        sscanf(str,"%s%s",entry[i].e,entry[i].f);
        i++;
        }
        qsort(entry,i,sizeof(Entry),cmp);
        while(gets(str))
        {
        index = BinSearch(str);
        if(index == -1)
        printf("ehn");
        else
        printf("%sn",entry[index].e);
        }
        return 0;
        }


        字符串哈希表,在《算法藝術與信息學競賽》推薦使用ELFHash函數,哈希沖突的處理采用鏈表法

        #include

        const int M = 149993;

        typedef struct
        {
        char e[11];
        char f[11];
        int next;
        }Entry;
        Entry entry[M];
        int i = 1;//詞典總條數
        int hashIndex[M];

        int ELFHash(char *key)
        {
        unsigned long h=0;
        while(*key)
        {
        h=(h<<4)+(*key++);
        unsigned long g=h&0Xf0000000L;
        if(g) h^=g>>24;
        h&=~g;
        }
        return h%M;
        }

        void find(char f[])
        {
        int hash = ELFHash(f);
        for(int k = hashIndex[hash]; k; k = entry[k].next)
        {
        if(strcmp(f, entry[k].f) == 0)
        {
        printf("%sn",entry[k].e);
        return;
        }
        }
        printf("ehn");
        }

        int main()
        {
        char str[22];
        while(gets(str))
        {
        if(str[0] == )
        break;
        sscanf(str,"%s %s",entry[i].e,entry[i].f);
        int hash = ELFHash(entry[i].f);
        entry[i].next = hashIndex[hash];
        hashIndex[hash] = i;
        i++;
        }
        while(gets(str))
        find(str);
        return 0;
        }


        評論


        技術專區

        關閉
        主站蜘蛛池模板: 尼勒克县| 隆回县| 拉孜县| 哈密市| 五华县| 阿拉善右旗| 南江县| 广西| 宣恩县| 疏勒县| 额尔古纳市| 涪陵区| 聂拉木县| 台东县| 如东县| 永城市| 虎林市| 阜阳市| 扎兰屯市| 灌云县| 武清区| 白朗县| 临泉县| 神池县| 开江县| 莱西市| 博乐市| 九龙县| 乌海市| 麦盖提县| 鄱阳县| 吉隆县| 延边| 驻马店市| 萨迦县| 临夏市| 策勒县| 社会| 翼城县| 离岛区| 石家庄市|