#include <iostream>
#include <ctime>
using namespace std;
const int NIL= -1;//为了简便,NIL设为-1
const int m = 20; //hash表大小
void InitHash(int T[m])
{
for (int i=0 ; i<m ; i++)
T[i] = NIL;
}
void PrintHash(int T[m])
{
for (int i=0 ; i< m ;i++)
cout << T[i] << " " ;
cout << endl;
}
int HashFunction(int value ,int i)
{//Hash函数要求对探查序列h(k,0),h(k,..),h(k,m)
//必须是<0,1....m-1>的一个排列,取简,我们取余
return (value+i)%m;
}
int HashInsert(int T[m], int k)
{
for (int i=0 ; i<m ; i++)
{
int j = HashFunction(k,i);
if (T[j] == NIL)
{
T[j] = k ;
return j ;
}
}
return NIL;//Hash overflow
}
int HashSearch(int T[m] ,int k)
{//在Hash表T中查找关键字k
int j=HashFunction(k,0);
for (int i=0 ; T[j] != NIL && i<m ; i++)
{
j = HashFunction(k,i);
if (T[j] == k)
return j;
}
return NIL ;
}
void HashDelete(int T[m] ,int k)
{//在Hash表T中删除关键字k
int j=HashSearch(T,k);//先找
if (j!=NIL)
T[j]=NIL;
else
cout << "Error" << endl;
}
int main(int argc ,char *argv[])
{
int Hash[m];
InitHash(Hash);
PrintHash(Hash);
srand(time(NULL));
int test[m];
for (int i=0 ; i<m ; i++)
{
test[i] = rand()%10; //为了验证查找,必须
cout << test[i] << " " ;
HashInsert(Hash,test[i]);
}
cout << endl;
PrintHash(Hash);
cout << HashSearch(Hash,3) << endl;
cout << HashSearch(Hash,48) << endl;
HashDelete(Hash,3);
PrintHash(Hash);
return 0;
}
hash操作
最新推荐文章于 2023-02-02 19:26:34 发布