#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASHSIZE 11
typedef struct
{
int ID;
char *name;
float salary;
}_employee;
_employee hash[HASHSIZE];
/*函数名:CreateHash
参数:employees为员工资料数组, size为数组大小
功能:将大小为size的员工资料数组按员工ID映射到Hash表*/
void CreateHash(_employee *employee,int size)
{
int i,j;
memset(hash,0,HASHSIZE);
for(i = 0;i < size;i++)
{
j = 0;
while(j < HASHSIZE)
{
if(hash[employee[i].ID % HASHSIZE + j].ID == 0)
{
hash[employee[i].ID % HASHSIZE + j] = employee[i];
break;
}
else
{
j++;
}
}
}
}
/*函数名:HashFun
参数:ID为员工ID
功能:将员工ID映射为Hash表中的下标地址
返回值:返回给定关键字对应的Hash表下标地址
*/
int HashFun(int ID)
{
return (ID % HASHSIZE);
}
/*冲突处理函数*/
int Collision(int address)
{
return (address + 1) % HASHSIZE;
}
/*打印员工信息函数*/
void PrintHash(_employee *employee)
{
printf("ID:%d \t name:%s \t salary:%f \n",
employee->ID,employee->name,employee->salary);
}
_employee HashValue(int key)
{
return hash[key % HASHSIZE];
}
/*哈希表查找函数*/
int HashSearch(int ID)
{
_employee temp;
int address, count = 0;
address=HashFun(ID);
count++;
temp=HashValue(address);
if(temp.ID == ID)
{
PrintHash(&temp);
return 1;
}
else if(temp.ID == 0)
{
printf("没有找到与您输入ID相关的记录!\n");
return 0;
}
else
{
while(count < HASHSIZE)
{
address=Collision(address);
temp=HashValue(address);
if(temp.ID == ID)
{
PrintHash(&temp);
return 1;
}
count++;
}
if(count == HASHSIZE)
printf("没有找到与您输入ID相关的记录!\n");
return 0;
}
}
int main(int argc, char* argv[])
{
_employee employee[]={
{1,"licky",8000},
{2,"shine",7000},
{3,"ada",10000},
{4,"joc",20000},
{12,"vicky",4000},
{13,"thile",2000}
};
int size,key;
size = sizeof(employee) / sizeof(employee[0]);
CreateHash(employee,size);
while(1)
{
printf("请输入一位员工的ID:\n ");
scanf("%d",&key);
HashSearch(key);
if(key == 0)
{
break;
}
}
return 0;
}