哈希表

 1 #include <stdio.h>
 2 #define HASH_LEN 13  //哈希表长度
 3 #define TABLE_LEN 8  //数据长度
 4 int data[TABLE_LEN] = {69, 65, 90, 37, 92, 6, 20, 54};
 5 int hash[HASH_LEN] = {0};    //initialize data is  0  初始化一个数组
 6 
 7 //将数值插入hash表中
 8 void InsertHash(int hash[], int m, int data)  
 9 {
10         int i;
11         i = data%13;    //get  hash address
12         while(hash[i]){ // the address used;判断冲突
13                 i++;  //解决冲突
14                 i = i % m;       
15         }
16         hash[i] = data;
17 }
18 
19 void CreateHash(int hash[], int m, int data[], int n)
20 {       
21         int i;
22         for(i=0;i<n;i++) //place the data to hash map
23         {         
24               InsertHash(hash, n, data[i]);
25         }
26 }
27 
28 int HashSearch(int hash[], int n, int key)
29 {
30         int i;
31         i = key%13; //get the hash address;
32         while(hash[i] &&hash[i]!=key) //is conflict?
33         {
34                 i++;
35                 i=i% n; //resolve confict       
36         }
37         if(hash[i]==0)
38                 return  -1;     //not find the data
39         else
40                 return i;       //find ok
41 }
42 
43 int main()
44 {
45         int key, i, pos;
46         CreateHash(hash, HASH_LEN, data, TABLE_LEN);    
47         printf("hash values: ");
48         for(i=0;i<HASH_LEN;i++)
49                 printf("%d  ", hash[i]);
50         printf("
");
51         printf("input the key data:");
52         scanf("%d", &key);
53 
54         pos = HashSearch(hash, HASH_LEN, key);
55         if(pos>=0)
56                 printf("find ok, pos is NO.%d 
", pos);
57         else
58                 printf("find error
");
59         return 0;
60 }
原文地址:https://www.cnblogs.com/chris-cp/p/4175988.html