1.原理简介
哈希查找是通过计算数据元素的存储地址进行查找的一种方法。⑴用给定的哈希函数构造哈希表;⑵根据选择的冲突处理方法解决地址冲突;⑶在哈希表的基础上执行哈希查找。构造哈希函数:直接定址法、数字分析法、平方取中法、折叠法、除留余数法、随机数法。冲突解决:开放定址法、链地址法。
2.代码实现
#define MaxSize 100 //定义最大哈希表长度
#define NULLKEY -1 //定义空关键字值
#define DELKEY -2 //定义被删关键字值
typedef int KeyType; //关键字类型
typedef char InfoType; //其他数据类型
typedef struct
{
KeyType key; //关键字域
InfoType data; //其他数据域
int count; //探查次数域
}HashTable[MaxSize]; //哈希表类型
void InsertHT(HashTable ha, int &n, KeyType k, int p) //将关键字k插入到哈希表中
{
int i, adr;
adr = k%p;
if (ha[adr].key == NULLKEY || ha[adr].key == DELKEY)
{ //x[j]可以直接放在哈希表中
ha[adr].key = k;
ha[adr].count = 1;
}
else //发生冲突时,采用线性探查法解决冲突
{
i = 1; //i记录x[j]发生冲突的次数
do
{
adr = (adr + 1) % p;
i++;
}
while (ha[adr].key != NULLKEY && ha[adr].key != DELKEY);
ha[adr].key = k;
ha[adr].count = i;
}
n++;
}
void CreateHT(HashTable ha, KeyType x[], int n, int m, int p) //创建哈希表
{
int i, n1 = 0;
for (i = 0; i<m; i++) //哈希表置初值
{
ha[i].key = NULLKEY;
ha[i].count = 0;
}
for (i = 0; i<n; i++)
InsertHT(ha, n1, x[i], p);
}
int SearchHT(HashTable ha, int p, KeyType k) //在哈希表中查找关键字k
{
int i = 0, adr;
adr = k%p;
while (ha[adr].key != NULLKEY && ha[adr].key != k)
{
i++; //采用线性探查法找下一个地址
adr = (adr + 1) % p;
}
if (ha[adr].key == k) //查找成功
return adr;
else //查找失败
return -1;
}
int DeleteHT(HashTable ha, int p, int k, int &n)//删除哈希表中关键字k
{
int adr;
adr = SearchHT(ha, p, k);
if (adr != -1) //在哈希表中找到关键字
{
ha[adr].key = DELKEY;
return 1;
}
else //在哈希表中未找到该关键字
return 0;
}
void DispHT(HashTable ha, int n, int m) //输出哈希表
{
float avg = 0;
int i;
cout << " 哈希表地址:" << “\t”;
for (i = 0; i < m; i++)
cout << setw(3) << i;
cout << endl;
cout << " 哈希表关键字:" << “\t”;
for (i = 0; i < m; i++)
{
if (ha[i].key == NULLKEY || ha[i].key == DELKEY)
cout << " “; //输出3个空格
else
cout << setw(3) << ha[i].key;//cout << setw(3) 相当于 printf(”%3d")
}
cout << endl;
cout << " 搜索次数:" << “\t”;
for (i = 0; i < m; i++)
{
if (ha[i].key == NULLKEY || ha[i].key == DELKEY)
cout << " “; //输出3个空格
else
cout << setw(3) << ha[i].count;
}
cout << endl;
for (i = 0; i < m; i++)
if (ha[i].key != NULLKEY && ha[i].key != DELKEY)
avg = avg + ha[i].count;
avg = avg / n;
cout << " 平均搜索长度ASL(” << n << “) = " << avg << endl;
}
void CompASL(HashTable ha, int m) //查找成功时,平均查找长度
{
int i,s = 0, n = 0;
for (i = 0; i<m; i++)
if (ha[i].key != DELKEY && ha[i].key != NULLKEY)
{
s = s + ha[i].count;
n++;
}
cout << " 查找成功的ASL=” << s1.0 / n << endl;
}
文章来源: https://blog.csdn.net/no_heart2019/article/details/96561492