哈希函数编程实现
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
#include
#include
#include
using namespace std;
class Hash;
class Node{//边节点类
public:
Node(char *ptr){
int len=strlen(ptr);
str=new char[len+1];
for(int i=0;i str[i]=ptr[i]; } str[len]='\0'; next=NULL; } ~Node(){delete []str;} friend class Hash;//定义为友元 private: char* str; Node*next; }; class Hash{//哈希散列表类 public: Hash(int len=0){//构造函数 length=len; count=0; head=new Node*[len]; for(int i=0;i head[i]=NULL; } file=NULL; } ~Hash(){//析构函数 ClearList();//用于清空哈希表中的数据 delete[]head; } void HashTest(int type){//运用哈希函数进行测试,tupe=0为BKDR,type=1为ELF,type=2为AP,type=3为自己设计哈希函数 ClearList();//用于清空散列表中的数据,进行新的哈希函数测试 file=fopen("data.txt","r");//指定读入文件为data.txt if(file==NULL){ cout<<"文件打开失败!"< return ; } char str[32];//假定每个字符长度不超过32 unsigned int position; while(!feof(file)){ count++; fscanf(file,"%s",str); if(type==0){ position=BKDRHash(str); }else if(type==1){ position=ELFHash(str); }else if(type==2){ position=APHash(str); }else{ position=MyHash(str); } position=position%length; Node *node=new Node(str); if(head[position]==NULL){ head[position]=node; }else{ Node*temp; temp=head[position]; while(temp->next!=NULL){ temp=temp->next; } temp->next=node; } } fclose(file); Assess(type);//计算桶使用率和平均桶长 } void SetFile(int num){//设计随机数据文件 ofstream fout("data.txt"); if(!fout.is_open()) { cout<<"无法打开输出流!!程序退出"< exit(0); } srand(time(0));//置随机数种子,一个随机数序列只需置一次。 for(int i=0;i int clength=1+rand()%32;//字符串的长度1到32,全字母字符串 for(int j=0;j int d=65+rand()%58; if(!('Z' char cname=(char)(d); fout< }else{ j--; } } if(i!=num-1) fout<<" "; } fout.close(); } void Display(){//查看哈希表内存存入状态 Node*temp; for(int i=0;i temp=head[i]; if(temp==NULL){ cout< }else{ cout< while(temp!=NULL){ cout< temp=temp->next; } cout< } } } private: void Assess(int type){//计算评价指标,输出到控制台 int backet_num=0; for(int i=0;i if(head[i]!=NULL){ backet_num++; } } backet_usage=(float)backet_num/length; avg_backet_len=(float)count/backet_num; if(type==0){ cout<<"测试"< cout<<"桶的使用率为:"<