哈希表
- 首先建立哈希函数,我用的是除留取余法,将哈希表的表长设置为11
- 处理冲突的方法为线性探测再散列的处理冲突方法
- 哈希表中记录在处理冲突时每个元素的比较次数,按照比较次数,最终可以算出该处理冲突方法的ASL
- 除了线性探测再散列的方法,还有二次探测再散列,随机探测再散列,链地址法
#include<stdio.h>
#include<stdlib.h>
#define Datatype int
#define MaxSize 100
#define HASHSIZE 11
typedef struct
{
Datatype data;
int times;
}HASHTABLE[MaxSize];
int HashFunc(int key);
void Creat(HASHTABLE ht, int DATA[], int n);
void HashInsert(HASHTABLE ht, int key);
int Collision(int di);
int Search(HASHTABLE ht, int num);
int main()
{
HASHTABLE ht;
int num;
int DATA[9] = { 19,01,23,14,55,68,11,82,36 };
Creat(ht, DATA, 9);
printf("输入要查询的数据:");
scanf("%d", &num);
if (Search(ht, num) != -1)
printf("Found!!!");
else
printf("Not Found!!!");
return 0;
}
int HashFunc(int key)
{
return key % HASHSIZE;
}
int Collision(int di)
{
return (di + 1) % HASHSIZE;
}
void Creat(HASHTABLE ht, int DATA[], int n)
{
int i;
for (i = 0; i < HASHSIZE; i++)
{
ht[i].data = NULL;
ht[i].times = 0;
}
for (i = 0; i < n; i++)
{
HashInsert(ht, DATA[i]);
}
printf("创建的哈希表如下:\n");
for (i = 0; i < n; i++)
{
printf("%d\t%d\t%d\n", i, ht[i].data, ht[i].times);
}
}
void HashInsert(HASHTABLE ht, int key)
{
int address;
int times = 1;
address = HashFunc(key);
if (ht[address].data == NULL)
{
ht[address].data = key;
ht[address].times++;
}
else
{
while (ht[address].data != NULL)
{
address = Collision(address);
times++;
}
ht[address].data = key;
ht[address].times = times;
}
}
int Search(HASHTABLE ht, int num)
{
int address;
address = HashFunc(num);
while (ht[address].data != NULL && ht[address].data != num)
{
address = Collision(address);
}
if (ht[address].data == num)
return address;
else
return -1;
}