#include <stdio.h>
#define N 13 /* N取素数 */
void insert_hash(int h[], int len, int key);
int search_hash(int h[], int len, int key);
int main()
{
int data[N] = { 0 }; /* 本例中数组中要存储的均为正数,初始化为全0表示值为空 */
int key; /* 待查关键字 */
int i;
for (i = 0; i < 6; i++) /* 存储数据 */
{
scanf("%d", &key);
insert_hash(data, N, key); /* 将值为key的关键字存入长度为N的数组data中 */
}
printf("Input a key you want to search: ");
scanf("%d", &key); /* 输入待查找的关键字 */
int index = search_hash(data, N, key); /* 在长度为N的数组data中查找关键字key */
if (index >= 0) /* 输出结果 */
printf("The index of the key is %d .\n", index);
else
printf("Not found.\n");
return 0;
}
/* 将值为key的关键字存入长度为N的数组data中 */
void insert_hash(int h[], int len, int key)
{
int i;
i = key % len; /* 用除留余数法计算出存储数据的位置 */
while (h[i] != 0) /* 如果该位置已经存储了数据,即发生了冲突 */
{
i++; /* 用线性探测法找后面的位置 */
i %= len; /* 如果越界了,将试探数组最开始的位置 */
}
h[i] = key; /* 存储关键字key */
}
/* 在长度为N的数组data中查找关键字key,返回存储数据的位置,-1代表没找到 */
int search_hash(int h[], int len, int key)
{
int i;
i = key % len; /* 用除留余数法计算出存储数据的位置 */
while (h[i] != 0 && h[i] != key) /* 确定的位置上不为空,也不是要找的数,这是由当时存储数据时发生过冲突所致 */
{
i++; /* 也用线性探测法找后面的位置 */
i %= len; /* 如果越界了,将试探数组最开始的位置 */
}
if (h[i] == 0) /* 找到的是空元素,说明没有找到 */
i = -1; /* 返回-1将代表没有找到 */
return i; /* 返回结果 */
}
哈希查找算法
最新推荐文章于 2024-04-19 20:13:15 发布