构造哈希函数的方法选择:除留余数法
由经验得知∶一般情况下,可以选p为质数或不包含小于20的质因数的合数
处理哈希冲突的方法:开放地址法
哈希表(开地址法)代码
#include<stdio.h>
#define NONE -1
#define m 16
#define p 13//除留余数法的除数,一般是比m小的最大素数H(key)=key mod p
typedef struct Hash
{
int key;//关键字
//InfoType otherinfo;//其他数据项
}Hash, HashTable[m];
void InitHashTable(HashTable ht)
{
for (int i = 0; i < m; i++)
{
ht[i].key = NONE;
}
}
static int H(int key)
{
return key % p;
}
//构建哈希表
//将key插入到哈希表ht中
bool Insert(HashTable ht, int key)
{
int hi = H(key);//得到key的哈希值
if (ht[hi].key == NONE)
{
ht[hi].key = key;
return true;
}
else
{
for (int d = 1; d < m; d++)
{
int newHi = (hi + d) % m;//公式
if (ht[newHi].key == key)//key已经存在,不再另外存储
{
return true;
}
else if (ht[newHi].key == NONE)
{
ht[newHi].key = key;
return true;
}
}
return false;//存满,没有空位
}
}
int Search(const HashTable ht, int key)
{
int hi = H(key);
for (int i = 0; i < m; i++)
{
int newHi = (hi + i) % m;
if (ht[newHi].key == key)
{
return newHi;
}
else if (ht[newHi].key == NONE)
{
break;
}
}
return -1;
}
void Show(HashTable ht)
{
for (int i = 0; i < m; i++)
{
printf("%d ", ht[i].key);
}
printf("\n");
}
int main()
{
HashTable ht;
InitHashTable(ht);
int arr[16] = { 3,5,7,1,2,9,28,25,6,11,10,15,17,23,24,19 };
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
Insert(ht, arr[i]);
}
Show(ht);
return 0;
}