查找の哈希表/哈希查找
散列函数采用的是 除留取余法;
冲突解决采用的是 开放定址法线性探测;
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define SUCCESS 1
#define OK 1
#define UNSUCCESS 0
#define HASHSIZE 10 //表长
#define NULLKEY -32768
typedef struct HashTable
{
int *elem;
int count; //当前数组元素个数
}HashTable, *pHashTable;
int m=0; //散列表长,全局变量
int InitHashTable(HashTable *H)
{
int i;
m=HASHSIZE;
H->count = m;
H->elem=(int *)malloc(m*sizeof(int));
for(i=0;i<m;i++)
{
H->elem[i] = NULLKEY;
}
return OK;
}
//散列函数
int Hash(int key)
{
return key % m; //除留余数法
}
void InsertHash(HashTable *H, int key)
{
int addr = Hash(key); //求散列地址
while(H->elem[addr] != NULLKEY) //若此时不为空,证明已经有值存入,冲突
addr = (addr+1) % m; //直到找到空位置插入即可
H->elem[addr] = key; //
}
int SearchHash(HashTable H, int key, int *addr)
{
*addr = Hash(key);
while(H.elem[*addr] != key)
{
*addr = (*addr+1) % m;
if(H.elem[*addr] == NULLKEY || *addr == Hash(key))
{ //若循环一圈都没有找到回到了原点,那么就说明关键字不存在
return UNSUCCESS;
}
}
return SUCCESS;
}
int main()
{
int keyarray[]={12,67,56,16,25,37,22,29,15,47,48,34};
struct HashTable H;
int addrr;
int key;
int i;
InitHashTable(&H);
for(i=0;i<HASHSIZE;i++)
{
InsertHash(&H, keyarray[i]);
}
key = 25;
SearchHash(H, key, &addrr);
printf("the key is %d, addr is %d\n", key, addrr);
}