一个哈希表使用实例

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值