Hash 表又称散列表,通过把关键字Key 映射到数组中的一个位置来访问记录,以加快查找速度。这个映射函数称为Hash函数,存放记录的数组称为Hash表。
Hash 函数
Hash函数的作用是把任意长度的输入,通过Hash算法变化成固定长度的输出,该输出就是Hash值。这种转化是一种压缩映射。一个好的Hash应该满足以下条件:每个关键字都可以均匀的分不到Hash表任意一个位置,并与其它已被散列到Hash表中的关键字不发生冲突。
使用PHP实现简单Hash表
/**
* HashTable.php
*
* @author RookieDream <983194768@qq.com>
* @version $Id RookieDream $
*/
require_once __DIR__ . '/HashNode.inc';
class HashTable
{
private $_buckets;
private $_size = 10;
/**
* 生成个一个固定大小的数组
*
* @return void
*/
public function __construct()
{
$this->_buckets = new SplFixedArray($this->_size);
}
/**
* hash 函数算法,根据键定位存往hash table 的那个位置
*
* @param $str $key 键
*
* @return hash table 的位置
*/
private function _hashFunc($key)
{
$strlen = strlen($key);
$hashval = 0;
for ($i=0; $i < $strlen; $i++) {
$hashval += ord($key[$i]);
}
return $hashval % $this->_size;
}
/**
* 向hash table插入一条记录
*
* @param string $key 键
* @param string $val 值
*
* @return void
*/
public function insert($key, $val)
{
$index = $this->_hashFunc($key);
if (isset($this->_buckets[$index])) {
$newNode = new HashNode($key, $val, $this->_buckets[$index]);
} else {
$newNode = new HashNode($key, $val);
}
$this->_buckets[$index] = $newNode;
}
/**
* 通过key 查找hash table中的记录
*
* @param string $key 键
*
* @return value 值
*/
public function find($key)
{
$index = $this->_hashFunc($key);
$current = $this->_buckets[$index];
while (isset($current)) {
if ($current->key == $key) {
return $current->value;
}
$current = $current->nextNode;
}
return NULL;
}
}
/**
*HashNode.php
*
* @author RookieDream <983194768@qq.com>
* @version $Id RookieDream $
*/
class HashNode
{
public $key;
public $value;
public $nextNode;
/**
* 初始化hash table 的节点
*
* @return void
*/
public function __construct($key, $value, $nextNode = NULL)
{
$this->key = $key;
$this->value = $value;
$this->nextNode = $nextNode;
}
}
demo
$ht = new HashTable();
$ht->insert('key1', 'key1');
$ht->insert('key2', 'value2');
$ht->insert('key12', 'value12');
$ht->insert('key21', 'value21');
echo $ht->find('key1');
echo $ht->find('key2');
echo $ht->find('key12');
echo $ht->find('key21');