/*
hash算法及应用:
hash表:根据hash函数建立的一张表,表中节点的存储地址即为hash函数的值
以输入变量为自变量,通过设定的hash函数求解hash(k)的值,即为输入变量k在hash表的存储地址
hash查找的优点:查找速度快;缺点:会发生存储冲突
*/
#include<iostream>
using namespace std;
#include<time.h>
#define n 100
struct hash{
int key; //关键值
int info; //存储的信息
}h[n];
//hash函数:hash(key)=key-1949
void createhash(){
time_t ts;
int i;
//设置随机数种子
srand((unsigned int)time(&ts));
for(int y=1949;y<=2016;y++){
i=y-1949;//hash地址
h[i].info=rand()%1000000;
}
}
//hash查找
void search(int year){
int i;
//判断查找的年份是否在查找范围内
if(year>=1949 && year<=2016){
//直接计算要查找年份的存储地址
i=year-1949;
cout<<year<<"年人数:"<<h[i].info<<endl;
}else {
cout<<"error\n";
}
}
//main函数
int main(){
int year;
createhash();
cout<<"请输入查找年份\n";
cin>>year;
search(year);
return 1;
}
查找算法之hash查找-1
最新推荐文章于 2023-06-13 02:42:17 发布