全域哈希C++实现

全域哈希代码的写法不唯一但是中心思想就是在构建插入时进行随机的使用哈希函数进行插入,一个元素投射到哈希表相同位置的函数有|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);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值