資料結構實踐 用雜湊法組織關鍵字

2021-07-08 10:57:50 字數 2105 閱讀 8411

本文是針對[資料結構基礎系列(8):查詢]中第11課時[雜湊表——雜湊結構]和第12課時[雜湊表的運算]的實踐專案。

【專案 - 用雜湊法組織關鍵字】

已知乙個關鍵字序列為if、while、for、case、do、break、else、struct、union、int、double、float、char、long、bool,共15個字串,雜湊函式h(key)為關鍵字的第乙個字母在字母表中的序號,雜湊表的表長為26。

(1)若處理衝突的方法採用線性探測法,請設計演算法,輸出每個關鍵字對應的h(key),輸出雜湊表,並求成功情況下的平均查詢長度。

[參考解答]

#include 

#include

#define n 15

#define m 26

int h(char *s)

int main()

; int i, j, k;

char ht[m][10];

int det[m]; //存放探測次數

for(i=0; i0]='\0';

det[i]=0;

}printf("字串 key\th(key)\n");

printf("------------------------\n");

for(i=0; is[i]); //求雜湊值

printf("%s\t\t%d\n", s[i],j);

k=0; //探測次數初值

while(1)

}det[j]=k;

}printf("---------------------\n");

printf("雜湊表\n");

printf("位置\t字串\t探查次數\n");

printf("---------------------\n");

for(i=0; iprintf("%d\t%s\t%d\n", i, ht[i], det[i]);

printf("---------------------\n");

k=0;

for(i=0; iprintf("查詢成功情況下的平均查詢長度 %f\n", 1.0

*k/n);

return

0;}

(2)若處理衝突的方法採用鏈位址法,請設計演算法,輸出雜湊表,並計算成功情況和不成功情況下的平均查詢長度。

[參考解答]

#include 

#include

#include

#define n 15

#define m 26

typedef

struct node //定義雜湊鍊錶的節點型別

lnode;

typedef

struct

httype;

int h(char *s) //實現雜湊函式

//構造雜湊表

void hash(char *s, httype ht)

}}//輸出雜湊表

void dispht(httype ht)

printf("\n");

}printf("---------------------\n");

}//求查詢成功情況下的平均查詢長度

double searchlength1(char *s, httype ht)

count+=k;

}return

1.0*count/n; //成功情況僅有n種

}//求查詢不成功情況下的平均查詢長度

double searchlength2(httype ht)

count+=k;

}return

1.0*count/m; //不成功時,在表長為m的每個位置上均可能發生

}int main()

; hash(s, ht);

dispht(ht);

printf("查詢成功情況下的平均查詢長度 %f\n", searchlength1(s, ht));

printf("查詢不成功情況下的平均查詢長度 %f\n", searchlength2(ht));

return

0;}

資料結構實踐 用雜湊法組織關鍵字

檔名稱 main.cpp 完成日期 2015年12月18日 版本號 codeblocks 問題描述 用雜湊法組織關鍵字 輸入描述 無 程式輸出 見執行結果 include include define n 15 define m 26 int h char s int main int i,j,k ...

用雜湊法組織關鍵字 2

問題及 檔名稱 main.cpp 完成日期 2015年12月13日 版本號 codeblocks 問題描述 用雜湊法組織關鍵字 輸入描述 無 程式輸出 見執行結果 include include include define n 15 define m 26 typedef struct node ...

專案2 用雜湊法組織關鍵字

檔名稱 main.cpp 完成日期 2015年12月7日 版本號 vc 6.0 問題描述 已知乙個關鍵字序列為if while for case do break else struct union int double float char long bool,共15個字串,雜湊函式h key 為...