使用PHP实现简单Hash表

      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');


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值