8622 哈希查找

**思路:**

  1. 初始化哈希表,长度为 `length`。

  2. 使用哈希函数 `H(k) = 3 * k % length` 计算哈希地址。

  3. 采用线性探测法处理冲突。

  4. 插入关键字序列到哈希表中。

  5. 计算平均查找长度。

**伪代码:**

  1. 初始化哈希表 `H`,长度为 `length`。

  2. 定义哈希函数 `Hash`。

  3. 定义冲突处理函数 `collision`。

  4. 定义查找函数 `SearchHash`。

  5. 定义插入函数 `InsertHash`。

  6. 读取输入的哈希表长度 `length`。

  7. 读取关键字序列,插入哈希表。

  8. 输出哈希表内容。

  9. 计算并输出平均查找长度。

**C++代码:**

复制代码
#include "malloc.h" /* malloc()等 */
#include "stdlib.h" /* exit() */
#include "stdio.h"
#define EQ(a,b) ((a)==(b))
#define SUCCESS 1
#define UNSUCCESS 0
#define NULLKEY -1 /*哈希表无元素时值为-1*/
typedef int ElemType;
int length;
typedef struct {
    ElemType *elem; /* 数据元素存储基址,动态分配数组 */
    int count; /* 当前数据元素个数 */
} HashTable;

void InitHashTable(HashTable *H) {
    int i;
    (*H).count = 0; /* 当前元素个数为0 */
    (*H).elem = (ElemType*)malloc(length * sizeof(ElemType));
    if (!(*H).elem)
        exit(0); /* 存储分配失败 */
    for (i = 0; i < length; i++)
        (*H).elem[i] = NULLKEY; /* 未填记录的标志 */
}

unsigned Hash(ElemType K) {
    return (3 * K) % length;
}

void collision(int *p) {
    *p = (*p + 1) % length; /* 线性探测再散列 */
}

int SearchHash(HashTable H, ElemType K, int *p, int *c) {
    *p = Hash(K); /* 求得哈希地址 */
    while (H.elem[*p] != NULLKEY && !EQ(K, H.elem[*p])) {
        (*c)++;
        if (*c < length)
            collision(p); /* 求得下一探查地址p */
        else
            break;
    }
    if EQ(K, H.elem[*p])
        return SUCCESS; /* 查找成功,p返回待查数据元素位置 */
    else
        return UNSUCCESS; /* 查找不成功(H.elem[p].key==NULLKEY),p返回的是插入位置 */
}

int InsertHash(HashTable *H, ElemType e) {
    int c, p;
    c = 0;
    if (SearchHash(*H, e, &p, &c)) /* 表中已有与e有相同关键字的元素 */
        printf("哈希表中已有元素%d。\n", e);
    else { /* 插入e */
        (*H).elem[p] = e;
        ++(*H).count;
    }
    return c + 1; /*查找长度为冲突次数加1*/
}

void TraverseHash(HashTable H) {
    int i;
    for (i = 0; i < length; i++)
        if (H.elem[i] == NULLKEY) /* 有数据 */
            printf("X ");
        else
            printf("%d ", H.elem[i]);
    printf("\n");
}

int main() {
    float i = 0, j = 0;
    ElemType e;
    HashTable H;
    scanf("%d", &length);
    InitHashTable(&H);
    scanf("%d", &e);
    while (e != -1) {
        j++; /*j记录输入元素个数*/
        i = i + InsertHash(&H, e); /*i记录查找长度的和*/
        scanf("%d", &e);
    }
    TraverseHash(H);
    printf("Average search length=%f\n", i / j);
    return 0;
}

**总结:**

  • 使用哈希函数 `H(k) = 3 * k % length` 计算哈希地址。

  • 采用线性探测法处理冲突。

  • 插入关键字序列到哈希表中,并计算平均查找长度。

相关推荐
小O的算法实验室6 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
小飞学编程...6 小时前
【哈希表】
数据结构·哈希算法·散列表
码匠许师傅6 小时前
【C++ 面试真题】26. 聊聊 C++ 的智能指针
java·c++·面试
Tbisnic7 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx7 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归8 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing9 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习9 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨9 小时前
基础数论总结
笔记·学习·算法
动词ing10 小时前
【C语言】结构体+文件基础
c语言·开发语言·数据结构