您的位置:首页 > 编程语言 > PHP开发

分块查找算法 (php)

2017-01-21 21:09 357 查看
class Node
{
public $data;
// 数据域
public $key; // 关键之查找
}
class IndexNode
{

public $key;
// 记录当前快中最大的key数
public $link; // 当地块的起始地址
}
function InitIndex(SplFixedArray $seqList)
{
$n = $seqList->count();
$s = ceil(sqrt($n));
$b = $s;
$indexList = new SplFixedArray($b);
for ($i = 0; $i < $s; $i ++) {
$max = null;
for ($j = 0; $j < $s; $j ++) {
if ($i * $s + $j < $n && $max < $seqList[$i * $s + $j]->key) {
$max = $seqList[$i * $s + $j]->key;
}
}
$idx = new IndexNode();
$idx->key = $max;
$idx->link = $i * $s;
$indexList[$i] = $idx;
}
return $indexList;
}

function searchIndex(SplFixedArray $seqList, SplFixedArray $indexList, $val)
{
$n = $seqList->count();
$m = ceil(sqrt($n));

for ($i = 0; $i < $m; $i ++) {
if ($seqList[$indexList[$i]->key]->data < $val)
continue;
$j = $indexList[$i]->link;
$end = $j + $m;
while ($j <= $end && $seqList[$j]->data != $val) {
$j ++;
}
if ($j > $end) {
continue;
} else {
return $j;
}
}
return -1;
}

$arr=[14,27,32,50,10,76,32,55,44,33,9,96,30,57,49];
$seqList = new SplFixedArray(count($arr));
for($i=0;$i<count($arr);$i++){
$node=new Node();
$node->key=$i;
$node->data=$arr[$i];
$seqList[$i]=$node;
}

$indexList = InitIndex($seqList);
$index=searchIndex($seqList, $indexList, 55);
print_r($index);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: