NodeJS实现哈希查找算法

 Python实现哈希查找算法

以下是一个简单的 Python 实现哈希查找算法的示例:

def hash_function(key, size):
    """简单哈希函数"""
    return key % size

def hash_search(hash_table, key):
    """哈希查找"""
    index = hash_function(key, len(hash_table))
    if hash_table[index] is not None:
        if hash_table[index] == key:
            return index
        else:
            # 处理哈希冲突
            next_index = (index + 1) % len(hash_table)
            while next_index != index:
                if hash_table[next_index] == key:
                    return next_index
                next_index = (next_index + 1) % len(hash_table)
    return None

# 示例
hash_table = [None] * 10  # 哈希表初始化为 None
data = [12, 25, 36, 20, 45, 55, 65, 75, 85]

# 插入数据到哈希表
for item in data:
    index = hash_function(item, len(hash_table))
    while hash_table[index] is not None:
        index = (index + 1) % len(hash_table)
    hash_table[index] = item

# 查找数据
key_to_search = 25
index = hash_search(hash_table, key_to_search)
if index is not None:
    print(f"元素 {key_to_search} 在索引 {index} 处找到。")
else:
    print(f"元素 {key_to_search} 未找到。")

在此示例中,我们使用简单的取模运算作为哈希函数,将关键字映射到哈希表的索引位置。如果该位置已被占用,则采用线性探测法处理冲突,即向后遍历哈希表,直到找到空闲位置

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值