#include <iostream>
using namespace std;
#define SUCCESS 1
#define UNSUCCESS 0
#define NULLKEY -32768
#define OK 1
//链地址法,哈希表是一个链表
typedef struct
{
int * elem; //数据元素存储的链表
int count; //当前数据元素个数
}HashTable;
int* arr; //全局变量,存放二次散列
void getHashTable(HashTable* H)
{
for (int i = 0; i < H->count; i++)
{
if (i != H->count - 1)
{
if (H->elem[i] != NULLKEY)
cout << H->elem[i] << " ";
else
cout << "NULL ";
}
else
{
if (H->elem[i] != NULLKEY)
cout << H->elem[i]<<endl;
else
cout << "NULL"<<endl;
}
}
}
//初始化散列表
int InitHashTable(HashTable* &H,int size)
{
int i;
H->count = size;
H->elem = new int [size];
for (int i = 0; i < size; i++)
H->elem[i] = NULLKEY; //链表数据区域赋空值
arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = 0; //链表数据区域赋空值
return OK;
}
//散列函数
int Hash(int key)
{
return key % 11;
}
//二次散列
int *doublevoid(HashTable *H)
{
int j = 0;
int* a = new int[(H->count)];
for (int i = 0; i < (H->count); i+=2,j++)
{
a[i] = (j + 1) * (j + 1);
a[i + 1] = -(j + 1) * (j + 1);
}
return a;
}
//插入关键字进散列表
void InsertHash(HashTable* &H, int key)
{
int addr = Hash(key);
int* a = doublevoid(H);
int i = 0;
while (H->elem[addr] != NULLKEY )
{
if (H->elem[addr] == key)
return;
int tem = (Hash(key) + a[i]);
if (tem < 0)
{
tem = H->count + (Hash(key) + a[i]);
}
addr = tem % H->count;
i++;
}
H->elem[addr] = key;
}
//散列表查找关键字
void SearchHash(HashTable *H, int key, int addr)
{
int i = 1;
int add = addr;
int* a = doublevoid(H);
while (H->elem[addr] != key)
{
int tem = (add + a[i-1]);
if (tem < 0)
{
tem = H->count + (add + a[i-1]);
}
if (H->elem[addr] == NULLKEY)
{
cout << "0 " << i << endl;
return;
}
i++;
addr = tem % H->count;
}
cout << "1 " << i << " " << addr + 1 << endl;
}
int main()
{
int t;
cin >> t; //次数
while (t--)
{
int m;
cin >> m; //哈希表长
int n;
cin >> n; //关键字个数
HashTable* ht = new HashTable();
InitHashTable(ht, m);
int num;
for (int i = 0; i < n; i++)
{
cin >> num;
InsertHash(ht, num);
}
getHashTable(ht);
int nn;
cin >> nn;
for (int i = 0; i < nn; i++)
{
cin >> num;
SearchHash(ht, num, Hash(num));
}
}
}
哈希查找—二次探测再散列
最新推荐文章于 2023-02-08 23:15:00 发布