思想:
添加额外的散列函数计算搜索命中的增量,即将线性探测时的+1(逐个后移检测);改为平移Hash2的值。
#include <iostream>
#include <stdlib.h>
#define GetKey(A) ( (A - 'A')%100 )
#define Hash(v, M) (v % M)
#define Hash2(v, M) (v % 5 + 1)
#define eq(A, B) (A == B)
#define NULLItem '\0'
#define MAX 20;//最大元素个数
typedef char Item;
typedef int KeyItem; //关键值类型
using namespace std;
static int M, N; //M:hash-size; N:element numbers
static Item* hash_table;
void HashTableInit(int max)
{
N = 0;
M = 2*max;
hash_table = new Item[M];
for(int i = 0; i < M; i++)
hash_table[i] = NULLItem;
}
void HashTableInsert(Item item)
{
int hash_key = Hash(GetKey(item), M);
int hash_key2 = Hash2(GetKey(item), M);
while (hash_table[hash_key] != NULLItem) {
// hash_key = (hash_key+1) % M; 线性探测时 +1
hash_key = (hash_key+hash_key2) % M;
}
hash_table[hash_key] = item;
N++;
}
Item HashTabelSearch(KeyItem v)
{
int hash_key = Hash(v, M);
int hash_key2 = Hash2(v, M);
while (hash_table[hash_key] != NULLItem) {
if(eq(GetKey(hash_table[hash_key]), v))
break;
hash_key = (hash_key+hash_key2) % M;
}
return hash_table[hash_key];
}
void HashTabelPrint()
{
cout << endl << "Print Hash Table: " << endl;
for(int i = 0; i < M; i++)
cout << i << "-" << hash_table[i] << " ";
cout << endl;
}
int main()
{
int max = MAX;
HashTableInit(max);
cout << "Item - Key - Hash_Key:"<< endl;
for (int i = 0; i < max; i++) {
Item item = 'A' + rand()%26;
cout << item << "-" << GetKey(item) << "-" <<Hash(GetKey(item), M) << "; ";
HashTableInsert(item);
}
cout << endl;
HashTabelPrint();
Item item = 'G';
KeyItem k = 8;
cout << endl;
cout << "Search key=" << k << ": " << HashTabelSearch(k) << endl;
cout << "Delete item=" << item << ": " <<endl;
// HashTabelDelete(item);
HashTabelPrint();
return 0;
}