php 算法 查找

(1) 二分查找

<?php
    //二分查找
    function bin_search($arr,$low,$high,$k)
    {
        if($low <= $high)
        {
            $mid = intval(($low + $high)/2);
            if($arr[$mid] == $k)
            {
                return $mid;
            }
            else if($k < $arr[$mid])
            {
                return bin_search($arr,$low,$mid-1,$k);
            }
            else
            {
                return bin_search($arr,$mid+1,$high,$k);
            }
        }
        return -1;
    }

    $arr = array(1,2,3,4,5,6,7,8,9,10);

    print(bin_search($arr,0,9,3));
?>
View Code

(2)顺序查找

function seq_search($arr,$n,$k)
{
    $array[$n] = $k;
    for ($i = 0; $i < $n; $i++) {
        if ($arr[$i] == $k) {
            return $i;
            break;
        }
    }
    return -1;
}
View Code

 

posted @ 2019-07-04 11:23  小跑跑泡  阅读(147)  评论(0编辑  收藏  举报