/**
* 定义数据元素类型
*/
class dataType
{
public $value;
public $hi;
}
/**
*定义哈希表
*/
class HashTable
{
public $data;
public $length;
public $num;
}
//创建哈希表
function createHashTable(&$H, $m, $p, $hash, $n)
{
$k=1;
$H->num = $n; // 初始哈希表的元素个数
$H->length = $m; // 初始哈希表的长度
for ($i = 0; $i < $m; $i ++) {
$dataType = new dataType();
$dataType->value = - 1;
$dataType->hi = 0;
$H->data[$i] = $dataType;
}
for ($i = 0; $i < $n; $i ++) {
$sum = 0;
$addr = $hash[$i] % $p;
$di = $addr;
if ($H->data[$addr]->value == -1) {
$H->data[$addr]->value = $hash[$i];
$H->data[$addr]->hi = 1;
} else {
do {
$di = ($di + $k) % $m;
$sum +=1;
} while ($H->data[$di] ->value != -1);
$H->data[$di]->value = $hash[$i];
$H->data[$di]->hi = $sum + 1;
}
}
}
//查找哈希表
function searchHash($H,$v)
{
$m=$H->length;
$d=$d1=$v%$m;
while($H->data[$d]->value!=-1)
{
if($H->data[$d]->value==$v){
return $d;
}else{
$d=($d+1)%$m;
}
if($d==$d1)
{
return -1;
}
}
return -1;
}
$hash = [78,90,66, 70,155,82,123,231];
$H = new HashTable();
$n = 8;
$m = 11;
$p = 11;
createHashTable($H, $m, $p, $hash, $n);
$point=searchHash($H,123);
哈希查找算法(php)
最新推荐文章于 2021-12-15 15:28:25 发布