php achieve binary search

<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'on');
 function binary_search($a ,$b = 0) {

    $low = 0;
    $hign = count($a) -1;
    while ($hign >= $low) {
        $mid = floor(($low + $hign)/2);
        if ($a[$mid] == $b) {
            return $a[$mid];
        } elseif ($a[$mid] > $b) {
            $hign = $mid - 1;
        } elseif($a[$mid] < $b) {
            $low = $mid + 1;
        }
    }
    return '没有相关字符';
 }
$a = [1,2,33,47,555,666,888];
$b =34;
echo binary_search($a,$b);

1, binary search log2n need to do more steps; - calculation of the number of power is the inverse.

Guess you like

Origin www.cnblogs.com/songyanan/p/12192844.html