用平方探测法来解决冲突的实现
头文件:
#ifndef HASHQUAD_H_INCLUDED
#define HASHQUAD_H_INCLUDED
typedef unsigned int Index;
typedef Index Position;
typedef int ElementType;
struct HashTbl;
typedef struct HashTbl *HashTable;
HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(ElementType Key,HashTable H);
void Insert(ElementType Key,HashTable H);
ElementType Retrieve(Position P,HashTable H);
HashTable ReHash(HashTable H);
#endif // HASHQUAD_H_INCLUDED
实现:
#include <stdio.h>
#include <stdlib.h>
#include "HashQuad.h"
#include <limits.h>
#include <math.h>
#define MinTableSize 100
enum KindOfEntry {Legitimate,Empty,Deleted};
struct HashEntry
{
ElementType Element;
enum KindOfEntry Info;
};
typedef struct HashEntry Cell;
struct HashTbl
{
int TableSize;
Cell *TheCells;
};
void Error(char *s)
{
}
void FatalError(char *s)
{
}
int IsPrime(int num)
{
if(num == 1) return 0;
int i;
for(i = 2; i <= sqrt(num); i++)
if(num%i == 0)
return 0;
return 1;
}
int NextPrime(int TableSize)
{
int i;
for(i = TableSize; i < INT_MAX; i++)
if(IsPrime(i))
return i;
return 0;
}
/* Boss 散列函数 Function of Hash */
Position Hash(const ElementType Key,int TableSize)
{
return Key%TableSize;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if(TableSize < MinTableSize)
{
Error("Table size too small");
return NULL;
}
H = malloc(sizeof(struct HashTbl));
if(H == NULL)
FatalError("Out of space!!!");
H->TableSize = NextPrime(TableSize);
H->TheCells = malloc(sizeof(Cell)*H->TableSize);
if(H->TheCells == NULL)
FatalError("Out of space!!!");
for(i = 0; i < H->TableSize; i++)
H->TheCells[i].Info = Empty;
return H;
}
Position Find(ElementType Key,HashTable H)
{
Position CurrentPos;
int CollisionNum;
CollisionNum = 0;
CurrentPos = Hash(Key,H->TableSize);
while(H->TheCells[ CurrentPos ].Info != Empty &&
H->TheCells[ CurrentPos ].Element != Key)
{
CurrentPos += ++CollisionNum << 1 - 1;
if(CurrentPos >= H->TableSize)
CurrentPos -= H->TableSize;
}
return CurrentPos;
}
void Insert(ElementType Key,HashTable H)
{
Position Pos;
Pos = Find(Key,H);
if( H->TheCells[ Pos ].Info != Legitimate )
{
H->TheCells[ Pos ].Info = Legitimate;
H->TheCells[ Pos ].Element = Key;
}
}
int main()
{
HashTable H = InitializeTable(1000);
Insert(10000,H);
Position P = Find(10000,H);
printf("%d\n",P);
return 0;
}
注:代码摘自《数据结构与算法分析第二版》