Skip to content

Commit

Permalink
Update HashTable.php
Browse files Browse the repository at this point in the history
实现哈希函数
  • Loading branch information
panxl6 committed Apr 9, 2019
1 parent ceef27d commit 3abe878
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions Write-hashtable-in-php/HashTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ class HashTale
private $size = 0;
private $container = null;

private $bigPrime = 1861;

public function __construct($size=1000)
{
// 哈希表的大小
Expand All @@ -21,8 +23,26 @@ private function getItemDefine()
);

return $item;
}

public function hashNum($key)
{
// $key不能太长,$this->bigPrime也不能太大,不然会引起整数溢出

$hashNum = 0;
$keyLen = strlen($key);

// 这里的**幂运算你也可以用位移来实现
for ($i=0; $i<$keyLen; $i++) {
$hashNum += ($this->bigPrime ** ($keyLen - ($i+1))) * ord($key[$i]);
}

$hashNum = $hashNum % $this->size;

return $hashNum;
}
}

$hashTable = new HashTale(2);
var_dump($hashTable);
$hashTable = new HashTale();

var_dump($hashTable->hashNum('hello'));

0 comments on commit 3abe878

Please sign in to comment.