哈希表

举报
nullptr; 发表于 2026/07/23 13:43:30 2026/07/23
【摘要】 /* * practice41_hash_table.c — 哈希表 (PG 核心数据结构) * ================================================================ * 对应 PG 模块: * src/backend/utils/hash/dynahash.c — 动态哈希表 * src/backend/execut...
/*
 * practice41_hash_table.c — 哈希表 (PG 核心数据结构)
 * ================================================================
 * 对应 PG 模块:
 *   src/backend/utils/hash/dynahash.c    — 动态哈希表
 *   src/backend/executor/nodeHashjoin.c  — Hash Join
 *   src/backend/executor/nodeHash.c      — Hash Aggregation
 *
 * 为什么重要:
 *   Hash Table 是 PostgreSQL 最常用的数据结构之一:
 *     - Hash Join: 构建 inner relation 的哈希表
 *     - Hash Aggregation: 按 GROUP BY 键构建哈希表
 *     - Hash Index: 基于哈希的索引结构
 *     - Catalog Cache: 系统表缓存
 *
 *   PG 的 dynahash 特点:
 *     - 动态扩容 (类似 std::unordered_map)
 *     - 链地址法解决冲突
 *     - 支持共享内存 (多进程访问)
 *
 * 核心概念:
 *   Hash Table = 数组 (桶) + 链表 (冲突处理)
 *
 *   示意图:
 *     buckets[0] → NULL
 *     buckets[1] → [K=1,V=10] → [K=9,V=90] → NULL  (冲突!)
 *     buckets[2] → [K=2,V=20] → NULL
 *     ...
 *     buckets[15] → [K=15,V=150] → NULL
 *
 *   插入 K=1, K=9 (都 hash 到 1):
 *     1. hash(1) % 16 = 1
 *     2. buckets[1] 为空, 直接插入
 *     3. hash(9) % 16 = 1
 *     4. buckets[1] 已有元素, 头插到链表
 *
 * 难度: ★★★☆☆ (链表操作 + 哈希函数)
 *
 * 学习目标:
 *   1. 哈希表原理 (hash 函数 + 冲突处理)
 *   2. 链地址法 (每个桶是链表头)
 *   3. 哈希函数设计 (简单取模 vs 复杂分布)
 *   4. 负载因子与扩容 (load factor = size / capacity)
 *
 * 核心公式:
 *   - 桶索引: bucket = hash(key) % capacity
 *   - 负载因子: load_factor = size / capacity
 *   - 扩容条件: load_factor > 0.75 (通常)
 *
 * PG 实际应用:
 *   - Hash Join: 构建哈希表 O(n), 探测 O(1)
 *   - Hash Agg: 按分组键构建哈希表
 *   - dynahash: PostgreSQL 的通用哈希表实现
 */

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

/* ============================================================
 * 基本结构
 * ============================================================ */

#define HT_CAPACITY 16  /* 桶数组大小 */
#define LOAD_FACTOR_THRESHOLD 0.75  /* 扩容阈值 */

/* 哈希表节点 (链表节点) */
typedef struct HashNode {
    int key;
    int value;
    struct HashNode *next;  /* 指向下一个冲突节点 */
} HashNode;

/* 哈希表结构 */
typedef struct HashTable {
    HashNode *buckets[HT_CAPACITY];  /* 桶数组 (每个桶是链表头) */
    int size;                          /* 当前元素个数 */
} HashTable;

/* ============================================================
 * TODO 1: 初始化/销毁
 * ============================================================ */

/* 初始化哈希表 */
void hash_table_init(HashTable *ht) {
    ht->size = 0;
    memset(ht->buckets, 0, sizeof(ht->buckets));
}

/* 创建新节点 */
HashNode *hash_node_create(int key, int value) {
    HashNode *node = (HashNode *)malloc(sizeof(HashNode));
    if(node!=NULL)
    {
        node->key = key;
        node->value = value;
        node->next = NULL;
    }
    return node;
}

/* ============================================================
 * TODO 2: 哈希函数
 * ============================================================ */

/* 简单哈希函数 (取模) */
int hash_function(int key) {
    return key % HT_CAPACITY;
}

/* ============================================================
 * TODO 3: 插入 (insert)
 * ============================================================ */

/*
 * 插入键值对
 *   如果 key 已存在, 更新 value
 *   如果 key 不存在, 头插到对应桶的链表
 */
void hash_table_insert(HashTable *ht, int key, int value) {
    /* TODO: 计算桶索引, 遍历链表查找 key */
    /* 提示: 找到 → 更新 value */
    /* 提示: 没找到 → 创建新节点, 头插到链表 */
    int index = hash_function(key);
    HashNode *node = ht->buckets[index];
    while(node != NULL)
    {
        if(node->key == key)
        {
            node->value = value;
            return;
        }
        node = node->next;
    }
    HashNode *newnode = hash_node_create(key,value);
    newnode->next = ht->buckets[index];
    ht->buckets[index]= newnode;
    ht->size++;
}

/* ============================================================
 * TODO 4: 查找 (lookup)
 * ============================================================ */

/*
 * 查找 key 对应的 value
 *   返回 1 如果找到, 0 如果没找到
 *   通过 out_value 返回找到的值
 */
int hash_table_lookup(HashTable *ht, int key, int *out_value) {

    int index = hash_function(key);
    HashNode *node = ht->buckets[index];
    while (node != NULL) {
        if(node->key == key)
        {
            *out_value = node->value;
            return 1;
        }
        node = node->next;
    }
    return 0;
}

/* ============================================================
 * TODO 5: 删除 (delete)
 * ============================================================ */

/*
 * 删除 key 对应的节点
 *   返回 1 如果删除成功, 0 如果 key 不存在
 */
int hash_table_delete(HashTable *ht, int key) {
    int index = hash_function(key);
    HashNode *node = ht->buckets[index];
    HashNode *prev = NULL;
    while(node !=NULL)
    {
        if(node->key == key)
        {
            if(prev == NULL)
            {
                ht->buckets[index] = node->next;
            }else {
                prev->next = node->next;
            }
            free(node);
            ht->size--;
            return 1;
        }
        prev = node;
        node = node->next;
    }
    return 0;
}

/* ============================================================
 * 工具函数 (已实现)
 * ============================================================ */

/* 打印哈希表状态 */
void hash_table_dump(HashTable *ht, const char *label) {
    printf("--- %s (size=%d) ---\n", label, ht->size);
    for (int i = 0; i < HT_CAPACITY; i++) {
        if (ht->buckets[i] != NULL) {
            printf("  buckets[%2d]:", i);
            HashNode *node = ht->buckets[i];
            while (node != NULL) {
                printf(" [K=%d,V=%d]", node->key, node->value);
                node = node->next;
            }
            printf("\n");
        }
    }
}

/* ============================================================
 * 测试
 * ============================================================ */

static void test_basic_operations(void) {
    printf("=== test_basic_operations ===\n");
    HashTable ht;
    hash_table_init(&ht);

    /* 初始状态 */
    assert(ht.size == 0);
    hash_table_dump(&ht, "初始 (空)");

    /* 插入几个元素 */
    hash_table_insert(&ht, 1, 10);
    hash_table_insert(&ht, 2, 20);
    hash_table_insert(&ht, 3, 30);
    hash_table_dump(&ht, "插入 K=1,2,3");
    assert(ht.size == 3);

    /* 查找存在的 key */
    int value;
    assert(hash_table_lookup(&ht, 1, &value) == 1);
    assert(value == 10);
    assert(hash_table_lookup(&ht, 2, &value) == 1);
    assert(value == 20);
    assert(hash_table_lookup(&ht, 3, &value) == 1);
    assert(value == 30);
    printf("  查找存在的 key: OK\n");

    /* 查找不存在的 key */
    assert(hash_table_lookup(&ht, 99, &value) == 0);
    printf("  查找不存在的 key: OK\n");

    /* 更新已存在的 key */
    hash_table_insert(&ht, 2, 200);  /* 更新 K=2 的 value */
    assert(hash_table_lookup(&ht, 2, &value) == 1);
    assert(value == 200);
    assert(ht.size == 3);  /* size 不变 */
    hash_table_dump(&ht, "更新 K=2 的 value");
    printf("  更新已存在的 key: OK\n");

    printf("  PASS\n\n");
}

static void test_collision(void) {
    printf("=== test_collision (冲突测试) ===\n");
    HashTable ht;
    hash_table_init(&ht);

    /* 插入会冲突的 key (假设 hash(1)=1, hash(17)=1) */
    hash_table_insert(&ht, 1, 10);
    hash_table_insert(&ht, 17, 170);  /* 与 K=1 冲突 */
    hash_table_insert(&ht, 33, 330);  /* 与 K=1,17 冲突 */
    hash_table_dump(&ht, "插入 K=1,17,33 (都 hash 到 1)");

    /* 验证都能找到 */
    int value;
    assert(hash_table_lookup(&ht, 1, &value) == 1);
    assert(value == 10);
    assert(hash_table_lookup(&ht, 17, &value) == 1);
    assert(value == 170);
    assert(hash_table_lookup(&ht, 33, &value) == 1);
    assert(value == 330);
    printf("  冲突元素都能找到: OK\n");

    /* 删除中间的节点 */
    assert(hash_table_delete(&ht, 17) == 1);
    assert(ht.size == 2);
    assert(hash_table_lookup(&ht, 17, &value) == 0);
    assert(hash_table_lookup(&ht, 1, &value) == 1);  /* 还在 */
    assert(hash_table_lookup(&ht, 33, &value) == 1); /* 还在 */
    hash_table_dump(&ht, "删除 K=17 (中间节点)");
    printf("  删除中间节点: OK\n");

    /* 删除头节点 */
    assert(hash_table_delete(&ht, 33) == 1);  /* 33 是头节点 (后插入) */
    assert(ht.size == 1);
    hash_table_dump(&ht, "删除 K=33 (头节点)");
    printf("  删除头节点: OK\n");

    printf("  PASS\n\n");
}

static void test_delete(void) {
    printf("=== test_delete ===\n");
    HashTable ht;
    hash_table_init(&ht);

    /* 插入多个元素 */
    for (int i = 1; i <= 10; i++) {
        hash_table_insert(&ht, i, i * 10);
    }
    hash_table_dump(&ht, "插入 K=1-10");
    assert(ht.size == 10);

    /* 删除存在的 key */
    assert(hash_table_delete(&ht, 5) == 1);
    assert(ht.size == 9);
    int value;
    assert(hash_table_lookup(&ht, 5, &value) == 0);
    printf("  删除 K=5: OK\n");

    /* 删除不存在的 key */
    assert(hash_table_delete(&ht, 99) == 0);
    assert(ht.size == 9);  /* size 不变 */
    printf("  删除不存在的 key (返回 0): OK\n");

    /* 删除全部 */
    for (int i = 1; i <= 10; i++) {
        if (i != 5) {  /* 5 已经删除 */
            assert(hash_table_delete(&ht, i) == 1);
        }
    }
    assert(ht.size == 0);
    hash_table_dump(&ht, "删除全部");
    printf("  删除全部: OK\n");

    printf("  PASS\n\n");
}

static void test_pg_scenario(void) {
    printf("=== test_pg_scenario (模拟 Hash Join) ===\n");

    /*
     * 模拟 PG Hash Join:
     *   表 A (inner): (1, 'A'), (2, 'B'), (3, 'C')
     *   表 B (outer): (2, 'X'), (3, 'Y'), (4, 'Z')
     *   JOIN ON A.id = B.id
     *
     *   步骤:
     *   1. 构建阶段: 扫描 A, 构建哈希表 (key=id, value=row)
     *   2. 探测阶段: 扫描 B, 用 B.id 探测哈希表
     */

    HashTable hash_table;
    hash_table_init(&hash_table);

    /* 构建阶段: 插入表 A 的数据 */
    printf("  构建阶段 (扫描表 A):\n");
    hash_table_insert(&hash_table, 1, 100);  /* A: (1, 100) */
    hash_table_insert(&hash_table, 2, 200);  /* A: (2, 200) */
    hash_table_insert(&hash_table, 3, 300);  /* A: (3, 300) */
    hash_table_dump(&hash_table, "哈希表 (表 A)");

    /* 探测阶段: 扫描表 B, 查找匹配 */
    printf("  探测阶段 (扫描表 B):\n");
    int value;

    /* B: (2, 'X') → 探测 id=2 */
    if (hash_table_lookup(&hash_table, 2, &value)) {
        printf("    匹配: B.id=2 → A.id=2 (A.value=%d)\n", value);
    }

    /* B: (3, 'Y') → 探测 id=3 */
    if (hash_table_lookup(&hash_table, 3, &value)) {
        printf("    匹配: B.id=3 → A.id=3 (A.value=%d)\n", value);
    }

    /* B: (4, 'Z') → 探测 id=4 */
    if (!hash_table_lookup(&hash_table, 4, &value)) {
        printf("    不匹配: B.id=4 (哈希表中不存在)\n");
    }

    printf("  Hash Join 模拟完成: OK\n");
    printf("  PASS\n\n");
}

int main(void) {
    printf("========================================\n");
    printf("practice41_hash_table.c — 哈希表\n");
    printf("========================================\n\n");

    test_basic_operations();
    test_collision();
    test_delete();
    test_pg_scenario();

    printf("========================================\n");
    printf("All tests passed!\n");
    printf("========================================\n");

    return 0;
}

/* ============================================================
 * 思考题
 * ============================================================
 *
 * 1. 为什么用链地址法而不是开放寻址法?
 *    (提示: 链地址法: 删除简单, 不受装载因子限制
 *           开放寻址: 缓存友好, 但删除复杂, 需要"墓碑"标记
 *           PG dynahash 用链地址法, 因为需要频繁删除)
 *
 * 2. 哈希函数的好坏如何评估?
 *    (提示: 均匀分布: 减少冲突
 *           计算快速: 不能成为瓶颈
 *           简单取模: 如果 key 本身分布均匀, 够用
 *           复杂 hash: MD5/CRC 等, 用于 key 分布不均匀时)
 *
 * 3. 为什么 PG 的 dynahash 支持动态扩容?
 *    (提示: 固定大小: 可能浪费空间或频繁冲突
 *           动态扩容: 负载因子 > 0.75 时扩容, 重新 hash
 *           缺点: 扩容时需要重新分配和 hash, 耗时
 *           PG 做法: 倍增容量, 分摊成本)
 *
 * 4. Hash Join 为什么比 Nested Loop 快?
 *    (提示: Nested Loop: O(n*m), 每行都要扫描整个表
 *           Hash Join: 构建 O(n) + 探测 O(m) = O(n+m)
 *           前提: 内存足够大, 能放下哈希表
 *           否则: 需要磁盘 spill, 性能下降)
 *
 * 5. 如何处理哈希表的内存泄漏?
 *    (提示: 删除节点时必须 free
 *           销毁哈希表时遍历所有桶, 释放所有节点
 *           PG 用 MemoryContext 管理, 避免手动 free)
 *
 * 6. 为什么头插而不是尾插?
 *    (提示: 头插: O(1), 直接修改桶指针
 *           尾插: O(n), 需要遍历到链表末尾
 *           头插缺点: 插入顺序反转, 但不影响正确性)
 *
 * 7. 如何实现并发安全的哈希表?
 *    (提示: 方案 1: 全局锁 (简单但性能差)
 *           方案 2: 分段锁 (每个桶或每组桶一个锁)
 *           方案 3: 无锁哈希表 (CAS 原子操作)
 *           PG 共享内存哈希表用 LWLock)
 *
 * 8. 哈希表 vs B-Tree 索引的区别?
 *    (提示: 哈希表: 等值查询 O(1), 不支持范围查询
 *           B-Tree: 等值 O(log n), 支持范围查询和排序
 *           PG hash index: 只适合等值查询
 *           PG btree index: 通用, 最常用)
 */

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。