php二分查找

// 递归版本
php二分查找
function bin_sch($arr,$low,$high,$val)
{
  if($low<$high){
                $mid = intval(($low+$high)/2);
                if($val == $arr[$mid]){
                    return $mid; 
                }else if($val < $arr[$mid]){
                     return bin_sch($arr,$low,$mid-1,$val);
                }else{
                    return bin_sch($arr,$mid+1,$high,$val);
                }       
        }
        return -1;
}                        
php二分查找

 

// 非递归版本
 
php二分查找
function bin_sch($arr,$val)
{
     $num = count($arr);
     $low = 0;
     $high = $c - 1;
     while($low <= $high){
          $mid = intval(($low + $high)/2);
          if($val <  $arr[$mid]){
              $mid++;
          }else if($val > $arr[mid]){
              $high--;
          }else{
              return $mid;
         }
     }   
     return -1;
}
php二分查找

 

 

php二分查找

上一篇:?【RequireJS】grunt-contrib-requirejs


下一篇:NO.A.0017——kali-linux2020.4配置固定IP地址/开启root权限/开启ssh