二分法查找,用少量的步数找到目标

<?php

function findNum($num,$max) {
    $arr = [];
    for($i = 0 ;$i< $max;$i++) {
        $arr[$i] = $i+1;
    }

    $step = 1;
    $start = 1;
    $end   = $max;
    $temp_target = intval(($start+$end)/2);

    while($temp_target != $num) {
        echo $temp_target;
        echo "<br>";

        $step += 1;
        if ($num > $temp_target) {
            $start = $temp_target;
        } else {
            $end   = $temp_target;
        }

        $temp_target = intval(($start+$end)/2);
    }
    echo "最终目标值:".$temp_target;
    echo "<br>";


    echo "步数".$step;
}

findNum(16,10000);

小结:
算法还蛮有意思的,将数学知识,用程序实现出来。尝试着自己模拟一下,蛮有趣。

原文地址:https://www.cnblogs.com/jiqing9006/p/7603456.html