雜湊技術【雜湊表】查詢演算法 PHP 版

勺顛顛發表於2019-08-13

雜湊技術:將記錄的儲存地址【雜湊地址】儲存在一塊連續的儲存單元中,這一塊儲存單元稱為雜湊表或叫雜湊表HashTable,根據雜湊【雜湊】函式f求得給定key的f(key)的對映,key對應的儲存地址稱為雜湊地址,跟數學中的函式差不多。
雜湊【雜湊】函式設計方法:
本文使用的是除留餘數數作為雜湊函式。
衝突解決方案:
開放定址法【中的線性探測法,每次加1向右探測】
五大查詢演算法:順序查詢,二分查詢,二叉樹查詢,索引查詢,hash表查詢

<?php
/**
 * Created by PhpStorm.
 * User: 1655664358@qq.com
 * Date: 2018/8/13
 * Time: 12:41
 */
define("HASHSIZE",5);

class Node
{
    private $data;
    private $index;
    public function setData($data)
    {
        $this->data = $data;
    }
    public function setIndex($data)
    {
        $this->index = $data;
    }
    public function getData()
    {
        return $this->data;
    }
    public function getIndex()
    {
        return $this->index;
    }
}
function hashData($data)
{
    return $data->getIndex()%HASHSIZE;
}
function insertNode(&$hashTable,$data)
{
    $hashAddress = hashData($data);
    while ($hashTable[$hashAddress]!=-1){
        $hashAddress = (++$hashAddress)%HASHSIZE;
    }
    $hashTable[$hashAddress] = $data;
}
function searchNode(&$hashTable,$data)
{
    $hashAddress = hashData($data);
    while ($hashTable[$hashAddress]->getIndex()!=$data->getIndex()){
        $hashAddress = (++$hashAddress)%HASHSIZE;
        if ($hashTable[$hashAddress]->getIndex()==-1||$hashAddress==hashData($data)){
            return -1;
        }
    }
    return $hashAddress;
}
(function(){

    $hashTable = [];
    for($i=0;$i<HASHSIZE;$i++){
        $hashTable[$i] = -1;
    }
    $node = new Node();
    $data = [
        [
            'index'=>1,
            'data'=>'php'
        ],
        [
            'index'=>3,
            'data'=>'python'
        ],
        [
            'index'=>2,
            'data'=>'java'
        ],
        [
            'index'=>5,
            'data'=>'arm'
        ],
        [
            'index'=>4,
            'data'=>'unix'
        ],
        [
            'index'=>3,
            'data'=>'linux'
        ],
    ];
    for ($j=0;$j<HASHSIZE;$j++){
        $obj = clone $node;
        $obj->setData($data[$j]['data']);
        $obj->setIndex($data[$j]['index']);
        insertNode($hashTable,$obj);
    }

    $obj = clone $node;
    $obj->setIndex(5);
    $result = searchNode($hashTable,$obj);

    $nodeResult = $hashTable[$result];
    echo $nodeResult->getData();
})();

相關文章