c語言構建哈希表


/*哈希查找
*哈希函數的構造方法常用的有5種。分別是:
*數字分析法
*平方取中法
*分段疊加
*偽隨機數
*除留取余法
*這里面除留取余法比較常用
*避免哈希沖突常用的方法有4種:
*開放定址法(線性探測再散列、二次探測再散列)
*鏈地址法
*再哈希法
*建立公共溢出區
其中,線性探測再散列比較常用*/
 

這是一道2009年武漢科技大學的考研題,但是按照要求卻做不出來,因為對7取模最多只有7個空間,不可能放進8個數,所以懷疑這道題是不是出錯了,但這是考研題,應該不會出錯吧。所以各位大神,你們怎么看?

以下是這道題的代碼實現,可以看到27放不進哈希表中,因為哈希表已滿!

 
 1 #include <stdio.h>  2 #include <time.h>  3 #define Max 7  4 #define Length 10  5 #define N 8  6  7 int hashtable[Length];  8  9 int func(int value) 10 { 11 return value % Max; 12 13 } 14 15 16 void create_hash(int key) 17 { 18 int pos, t; 19 pos = func(key); 20 printf(" %d MOD %d = %d\n", key, Max, pos); 21 t = pos; 22 while(hashtable[t] != -1) 23  { 24 printf("(%d+1) MOD %d = %d\n", t, Max, (t+1) % Max); 25 t = (t+1) % Max; 26 27 if(pos == t) 28  { 29 30 printf("Hash table is full!\n"); 31 return; 32  } 33 34  } 35 hashtable[t] = key; 36 37 } 38 39 main() 40 { 41 int flag[N] = {75, 33, 52, 41, 12, 88, 66, 27}; 42 int i, j, t; 43 for(i = 0; i < Length; i++) 44 hashtable[i] = -1; 45 46 i = 0; 47 while(i != N) 48  { 49 t = flag[i]; 50 51  create_hash(t); 52 printf(" ------------------------------------------------------------\n"); 53 printf(" | 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 |\n"); 54 printf(" ------------------------------------------------------------\n"); 55 printf("%2d: ", t); 56 for(j = 0; j < Length; j++) 57 printf("| %2d |", hashtable[j]); 58 59 printf("\n"); 60 printf(" ------------------------------------------------------------\n"); 61 62 i++; 63 64 65  } 66 67 }

 

運行結果:

 

 

問題解決了!感謝可愛又靠譜的老師和幫我轉發消息的baby

之前的理解有誤,以為不論是第一次代入函數計算還是處理沖突都是對函數給定的值取余,正確的是哈希函數函數給定的值取余,處理沖突表長取余。代碼更正如下:

 

/*哈希查找 *哈希函數的構造方法常用的有5種。分別是: *數字分析法 *平方取中法 *分段疊加 *偽隨機數 *除留取余法 *這里面除留取余法比較常用 *避免哈希沖突常用的方法有4種: *開放定址法(線性探測再散列、二次探測再散列) *鏈地址法 *再哈希法 *建立公共溢出區 其中,線性探測再散列比較常用*/ #include <stdio.h> #include <time.h> #define Max 7 #define Length 10 #define N 8 int hashtable[Length]; int func(int value) { return value % Max; } void create_hash(int key) { int pos, t; pos = func(key); printf(" %d MOD %d = %d\n", key, Max, pos); t = pos; while(hashtable[t] != -1) { printf("(%d+1) MOD %d = %d\n", t, Length, (t+1) % Length); t = (t+1) % Length; if(pos == t) { printf("Hash table is full!\n"); return; } } hashtable[t] = key; } main() { int flag[N] = {75, 33, 52, 41, 12, 88, 66, 27}; int i, j, t; for(i = 0; i < Length; i++) hashtable[i] = -1; i = 0; while(i != N) { t = flag[i]; create_hash(t); printf(" ------------------------------------------------------------\n"); printf(" | 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 |\n"); printf(" ------------------------------------------------------------\n"); printf("%2d: ", t); for(j = 0; j < Length; j++) printf("| %2d |", hashtable[j]); printf("\n"); printf(" ------------------------------------------------------------\n"); i++; } }

 

運行結果:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM