分块查找算法 (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;$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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值