求数据结构大神指教 关于哈希查找
题目要求如下
现有十万个由5到9个含大小写英文字符组成姓名的数据库在就业中心,要你设计尽可能优的哈希查找方法,使查找的效率高(即平均查找长度尽可能小),要求最终的平均查找长度不超过5。要求:
1、根据大小写英文字符组成的姓名,构成合适的关键字值(key);
2、设计一个合理的哈希函数;
3、选用一个合适的解决冲突的办法;
4、对于开放定址法,对于建议填充因子在0.6-0.8之间。
5、建立哈希表(关键字和成功查找次数);
6、利用学过的知识直接计算查找成功时的平均查找长度。
7、根据随机生成的测试数据,求出实际情况下的平均查找长度(可能同时包含查找成功或失败的情况)。
这是我写的已经构建好哈希表的算法
但是为什么第68行的 ht.elem[p]=e; 这句代码没办法把 e 的数据传递到 ht 中
#include<iostream>
#include<string>
using namespace std;
const int Maxsize=160000;
const int MaxS=100000;
const int MaxSize=159979;
typedef int KeyType;
const char inputfile[MaxS]="D:\\input.txt";
const char testfile[MaxS]="D:\\test.txt";
const char outputfile[MaxS]="D:\\output.txt";
struct ElemType{
int Key;
string name;
int cnt;
};
struct HashTable
{
ElemType *elem;
};
unsigned int Hash(string s) {
unsigned int h = 0;
for(int i=0; i<s.size(); i++) {
h = 31 * h + s[i];
}
return h % MaxSize;
}
int NextPos(int p)
{
return (p+1)%MaxSize;
}
double sum=0;
bool SearchHash(HashTable ht,string k,int &p)
{
int cnt=1;
p=Hash(k);
while(ht.elem[p].name!="0"&&ht.elem[p].name!=k)
{
cnt++;
p=NextPos(p);
}
if(ht.elem[p].name==k)
{
ht.elem[p].cnt=cnt;
sum=sum+ht.elem[p].cnt;
return true;
}
else
{
return false;
}
}
bool InsertHash(HashTable &ht,ElemType e)
{
int p;
if(SearchHash(ht,e.name,p)==true)
return false;
else
{
ht.elem[p]=e;
return true;
}
}
void Init(HashTable &ht,int n)
{
ht.elem=new ElemType[n];
for(int i=0;i<n;i++)
{
ht.elem[i].Key=0;
ht.elem[i].name="0";
ht.elem[i].cnt=0;
}
}
void create(HashTable &ht,int n)
{
Init(ht,Maxsize);
for(int i=0;i<n;i++)
{
ElemType e;
char s[10];
scanf("%s", s);
e.name=s;
e.Key=Hash(e.name);
InsertHash(ht,e);
}
}
void run()
{
HashTable ht;
int n;
n=100000;
create(ht,n);
}
int main(){
double yinzi,ASL;
cout<<"正在构造哈希表,请稍等......\n\n";
freopen("inputfile","r",stdin);
run();
sum=sum/100000;
ASL=sum;
cout<<sum<<endl;
cout<<"填充因子:";
yinzi=(double)MaxS/(double)Maxsize;
cout<<yinzi<<endl;
cout<<endl;
cout<<"哈希表构造完毕!\n\n";
cout<<"查找成功时的平均查找长度:";
cout<<ASL<<endl;
cout<<endl;
while(true){
freopen("con","r",stdin);
int cmd;
cout<<"=============================================\n";
cout<<"请选择测试方式:\n";
cout<<"=============================================\n";
cout<<"1:文件测试\n";
cout<<"2:键盘输入(输入字符0表示结束测试)\n";
cout<<"0:Return\n";
cin>>cmd;
if(cmd==1){
freopen("testfile","r",stdin);
freopen(outputfile,"w",stdout);
}
else if(cmd==2){
freopen("con","w",stdout);
freopen("con","r",stdin);
}
else if(cmd==0){
break;
}
else{
cout<<"Error input, Try again!\n";
continue;
}
}
return 0;
}