分块查找算法 (php)

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;$ikey=$i;
    $node->data=$arr[$i];
    $seqList[$i]=$node;
}


$indexList = InitIndex($seqList);
$index=searchIndex($seqList, $indexList, 55);
print_r($index);

你可能感兴趣的:(php)