哈希查找c语言代码

本文介绍了哈希查找算法的基本思想和一个使用C语言实现的哈希表例子。通过将数据映射到散列表,并利用简单的计算进行查找,提高了在大数据集中的搜索效率。示例代码展示了哈希函数的定义、插入、搜索和删除操作。
摘要由CSDN通过智能技术生成

哈希查找是一种快速查找数据的算法,通常用于在大型数据集中查找特定元素。它的基本思想是将数据映射到一个散列表,然后通过简单的计算来查找数据。

下面是一个哈希查找的例子,使用 C 语言实现:

``` #include <stdio.h> #include <stdlib.h> #include <string.h>

#define SIZE 20

struct DataItem { int data;
int key; };

struct DataItem* hashArray[SIZE]; struct DataItem* dummyItem; struct DataItem* item;

int hashCode(int key) { return key % SIZE; }

struct DataItem *search(int key) { // 获取哈希值 int hashIndex = hashCode(key);

// 移动到哈希表的对应位置 while(hashArray[hashIndex] != NULL) {

if(hashArray[hashIndex]->key == key)
     return hashArray[hashIndex]; 
        
  <
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的哈希表C语言实现代码,使用链地址法解决哈希冲突: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define HASHSIZE 12 #define NULLKEY -32768 typedef struct { int *elem; // 数据元素存储基址,动态分配数组 int count; // 当前数据元素个数 } HashTable; int InitHashTable(HashTable *H) { int i; H->count = HASHSIZE; H->elem = (int *)malloc(HASHSIZE * sizeof(int)); for (i = 0; i < HASHSIZE; i++) { H->elem[i] = NULLKEY; } return 1; } int Hash(int key) { return key % HASHSIZE; // 散列函数采用除留余数法 } void InsertHash(HashTable *H, int key) { int addr = Hash(key); // 求哈希地址 while (H->elem[addr] != NULLKEY) { // 如果不为空,则冲突 addr = (addr + 1) % HASHSIZE; // 开放定址法的线性探测 } H->elem[addr] = key; // 直到有空位后插入关键字 } int SearchHash(HashTable H, int key) { int addr = Hash(key); // 求哈希地址 while (H.elem[addr] != key) { // 如果不相等,则冲突 addr = (addr + 1) % HASHSIZE; // 开放定址法的线性探测 if (H.elem[addr] == NULLKEY || addr == Hash(key)) { // 如果循环回到原点或者遇到空位,则说明关键字不存在 return -1; } } return addr; // 找到关键字,返回其地址 } int main() { HashTable H; int i, key, result; InitHashTable(&H); printf("请输入%d个数:\n", HASHSIZE); for (i = 0; i < HASHSIZE; i++) { scanf("%d", &key); InsertHash(&H, key); } printf("哈希表中的数据为:\n"); for (i = 0; i < HASHSIZE; i++) { printf("%d ", H.elem[i]); } printf("\n请输入要查找的数:\n"); scanf("%d", &key); result = SearchHash(H, key); if (result == -1) { printf("没有找到%d\n", key); } else { printf("%d的位置是%d\n", key, result); } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值