Hash查找算法
转自:http://blog.csdn.net/wuxiaoer717/article/details/6863113
根据关键字的结构和分布的不同,可构造出许多不同的哈希函数,这里主要介绍两种常用的整数类型关键字的哈希函数构造方法。
1)直接定址法
H(Key) = key 或H(key) = a x key + b;
2)除留余数法
H(key) = key MOD p ——(p <= m)
hash冲突的处理方法
处理哈希冲突的方法可分为开放定址法和链地址法两大类:
1)开放定制法:
就是当冲突发生时,使用某种探测方法在哈希表中形成一个探测序列。沿此序列逐个单元地查找,直到找到给定的关键字,或者碰到一个空的地址单元为止,
在开放定制法中,哈希表中的空闲单元(假设其下表为d)不仅允许哈希地址为d的同义词关键字使用,而且也允许发生冲突的其他关键字使用,因为这些关键字
的哈希地址不为d,所以称其为非同义词关键字。
Hi=(H(key)+di) MOD m ——i = 1,2,...,k(k<=m-1)
其中H(key)为哈希函数, m为哈希表表长, di为增量序列, 若di=1,2,3,4.。。m-1,则称为线性探测再散列;
若di = 1, -1, 4, -4.。。。。。则称其为二次探测再散列。
2)链地址法:
把所有的同义词链接在同一个单链表中,在这种方法中,哈希表每个单元中存在的不再是对象,而是相应同义词单链表的头指针。
代码实现如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 5 #define Hashmax 11 6 #define MAX 20 7 8 9 typedef int ElemType; 10 11 12 typedef struct HashNode 13 { 14 ElemType elem; 15 struct HashNode *next; 16 }HashNode; 17 18 19 typedef struct 20 { 21 HashNode ChainHash[MAX]; 22 int count; 23 }HashTable; 24 25 26 int hash_mod(ElemType key) 27 { 28 return key % Hashmax; 29 } 30 31 32 void InsertHash(HashTable *h, int key) 33 { 34 HashNode *p; 35 int index; 36 p = (HashNode*)malloc(sizeof(HashNode)); 37 p->elem = key; 38 index = hash_mod(key); 39 p->next = h->ChainHash[index].next; 40 h->ChainHash[index].next = p; 41 h->count++; 42 } 43 44 45 void CreateHashTable(HashTable *h, int n) 46 { 47 int key; 48 int i; 49 for(i = 0; i < n; i++) 50 { 51 printf("Input the %d key :", i+1); 52 scanf("%d", &key); 53 InsertHash(h, key); 54 } 55 } 56 57 58 void PrintHashTable(HashTable *h) 59 { 60 int i; 61 HashNode *p; 62 for(i = 0;i <= Hashmax; i++) 63 { 64 p = h->ChainHash[i].next; 65 while(p) 66 { 67 printf("%-5d", p->elem); 68 p = p->next; 69 } 70 } 71 } 72 73 74 int SearchHash(HashTable *h, int key) 75 { 76 HashNode *p; 77 int index; 78 int counter = 0; 79 index = hash_mod(key); 80 p = h->ChainHash[index].next; 81 while(p) 82 { 83 if(p->elem == key) 84 return 1; 85 else 86 p = p->next; 87 } 88 return 0; 89 } 90 91 92 93 94 void main() 95 { 96 int n ,key; 97 int i; 98 HashTable H; 99 printf("input the length of the Hash that we want to build:"); 100 scanf("%d", &n); 101 for(i = 0;i <= Hashmax; i++) 102 H.ChainHash[i].next = NULL; 103 H.count = 0; 104 CreateHashTable(&H,n); 105 106 107 printf("The hash table that we build is:"); 108 PrintHashTable(&H); 109 110 111 printf("\nInput the key that we want to search(-1 for exit):"); 112 scanf("%d", &key); 113 while(key != -1) 114 { 115 if(SearchHash(&H, key)) 116 printf("There is a %d record in the Hash Table!\n", key); 117 else 118 printf("There is not a %d record in the Hash Table!\n", key); 119 120 121 printf("\nInput the key that we want to search(-1 for exit):"); 122 scanf("%d", &key); 123 } 124 }

浙公网安备 33010602011771号