Python实现哈希查找算法


​ 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} 未找到。")

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

Python10.jpg

​ 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} 未找到。")

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

Python10.jpg

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在