算法导论 - 基于 C# 的散列函数实现
散列函数(Hash Function)是散列表的核心组件,它将输入(键)转换为固定大小的整数,这个整数通常用于索引数组中的位置。散列函数的目标是尽量均匀地分布输入数据,以减少冲突的发生。
散列函数的特性
- 确定性:相同的输入总是产生相同的输出。
- 高效性:计算哈希值的时间应该很短。
- 均匀分布:应将输入数据尽量均匀地分布到哈希表的所有位置上。
- 抗碰撞:尽量减少不同输入产生相同哈希值的情况。
代码实现
下面是 C# 中实现的一个简单的字符串散列函数和基于链地址法的散列表:
using System;
using System.Collections.Generic;
public class HashTable<TKey, TValue>
{
private readonly int size;
private readonly LinkedList<KeyValuePair<TKey, TValue>>[] items;
public HashTable(int size)
{
this.size = size;
items = new LinkedList<KeyValuePair<TKey, TValue>>[size];
}
// 哈希函数
protected int GetArrayPosition(TKey key)
{
int hash = key.GetHashCode();
int position = hash % size;
return Math.Abs(position);
}
public void Insert(TKey key, TValue value)
{
int position = GetArrayPosition(key);
LinkedList<KeyValuePair<TKey, TValue>> linkedList = GetLinkedList