全域哈希代码的写法不唯一但是中心思想就是在构建插入时进行随机的使用哈希函数进行插入,一个元素投射到哈希表相同位置的函数有|H|/m个,|H|为集合中函数总个数,m为槽数
#include
#include
#include<stdlib.h>
#include<time.h>
using namespace std;
#define random(x)(rand()%x)
const int m = 16;
const int n = 13;
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType otherinfo;
}HashTable[m];
int Insertliuyu(HashTable Ht, KeyType key)//除数留余法
{
int Ho = key % n;//n为小于表长的最大质数
if (Ht[Ho].key == 0)
{
Ht[Ho].key = key;
return 1;
}
else
return 0;
}
//开放定址法
int Insertding1(HashTable Ht, KeyType key)//线性探测再散列
{
int Ho = key % n;//n为小于表长的最大质数
int Hi;
for (int i = 0; i < m; i++)
{
Hi = (Ho + i) % m;
if (Ht[Hi].key == 0)
{
Ht[Hi].key = key;
return 1;
}
}
return 0;
}
int Insertding2(HashTable Ht, KeyType key)//二次探测再散列
{
int Ho = key % n;//n为小于表长的最大质数
int Hi;
for (int i = 0; i < m / 2; i++)
{
Hi = (Ho + i * i) / m;
if (Ht[Hi].key == 0)
{
Ht[Hi].key = key;
return 1;
}
else
{
Hi = (Ho - i * i) / m;
if (Ht[Hi].key == 0)
{
Ht[Hi].key = key;
return 1;
}
}
}
return 0;
}
int Insertding3(HashTable Ht, KeyType key)//伪随机探测再散列
{
int Hi;
srand((int)time(0));
int q = m;
while (q--)
{
Hi = random(m);
if (Ht[Hi].key == 0)
{
Ht[Hi].key = key;
return 1;
}
}
return 0;
}
int AllHash(HashTable Ht, KeyType key)//全域哈希
{
srand((int)time(0));
int flage = 0;
while (flage != 1)
{
int q = random(4);
if (q == 0)
{
flage = Insertliuyu(Ht, key);
}
else if (q == 1)
{
flage = Insertding1(Ht, key);
}
else if (q == 2)
{
flage = Insertding2(Ht, key);
}
else if (q == 3)
{
flage = Insertding3(Ht, key);
}
}
if (flage == 1)
return 1;
else
return 0;
}
int main()
{
HashTable HT;
for (int i = 0; i < m; i++)
{
HT[i].key = 0;
}
//插入
AllHash(HT, 19);
AllHash(HT, 14);
AllHash(HT, 23);
AllHash(HT, 1);
AllHash(HT, 68);
AllHash(HT, 20);
AllHash(HT, 84);
AllHash(HT, 27);
AllHash(HT, 55);
AllHash(HT, 11);
AllHash(HT, 10);
AllHash(HT, 79);
for (int i = 0; i < m; i++)
{
printf("%d,", HT[i].key);
}
}