根据关键字的结构和分布的不同,可构造出许多不同的哈希函数,这里主要介绍两种常用的整数类型关键字的哈希函数构造方法。
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)链地址法:
把所有的同义词链接在同一个单链表中,在这种方法中,哈希表每个单元中存在的不再是对象,而是相应同义词单链表的头指针。
代码实现如下:
#include <stdio.h>
#include <stdlib.h>
#define Hashmax 11
#define MAX 20
typedef int ElemType;
typedef struct HashNode
{
ElemType elem;
struct HashNode *next;
}HashNode;
typedef struct
{
HashNode ChainHash[MAX];
int count;
}HashTable;
int hash_mod(ElemType key)
{
return key % Hashmax;
}
void InsertHash(HashTable *h, int key)
{
HashNode *p;
int index;
p = (HashNode*)malloc(sizeof(HashNode));
p->elem = key;
index = hash_mod(key);
p->next = h->ChainHash[index].next;
h->ChainHash[index].next = p;
h->count++;
}
void CreateHashTable(HashTable *h, int n)
{
int key;
int i;
for(i = 0; i < n; i++)
{
printf("Input the %d key :", i+1);
scanf("%d", &key);
InsertHash(h, key);
}
}
void PrintHashTable(HashTable *h)
{
int i;
HashNode *p;
for(i = 0;i <= Hashmax; i++)
{
p = h->ChainHash[i].next;
while(p)
{
printf("%-5d", p->elem);
p = p->next;
}
}
}
int SearchHash(HashTable *h, int key)
{
HashNode *p;
int index;
int counter = 0;
index = hash_mod(key);
p = h->ChainHash[index].next;
while(p)
{
if(p->elem == key)
return 1;
else
p = p->next;
}
return 0;
}
void main()
{
int n ,key;
int i;
HashTable H;
printf("input the length of the Hash that we want to build:");
scanf("%d", &n);
for(i = 0;i <= Hashmax; i++)
H.ChainHash[i].next = NULL;
H.count = 0;
CreateHashTable(&H,n);
printf("The hash table that we build is:");
PrintHashTable(&H);
printf("\nInput the key that we want to search(-1 for exit):");
scanf("%d", &key);
while(key != -1)
{
if(SearchHash(&H, key))
printf("There is a %d record in the Hash Table!\n", key);
else
printf("There is not a %d record in the Hash Table!\n", key);
printf("\nInput the key that we want to search(-1 for exit):");
scanf("%d", &key);
}
}